【发布时间】:2015-03-10 12:38:24
【问题描述】:
我有一个方法试图找到对象中存在的 Hash 类型的集合并向该集合中添加一个新元素。现在我有以下sn-p:
/// <summary>
/// Adds an element to a list
/// </summary>
/// <param name="target">The object that contains the collection of the type we are searching for.</param>
/// <param name="toAdd">the object to add to the collection.</param>
/// <param name="propertyType">The type of the object we want to add to the collection.</param>
public void AddValueCollection(object target, object toAdd, Type propertyType)
{
PropertyInfo propertyInfo = target.GetType().GetProperties().FirstOrDefault(o => o.PropertyType.GenericTypeArguments.Length > 0
&& o.PropertyType.GenericTypeArguments[0] == propertyType);
if (propertyInfo != null)
{
object cln = propertyInfo.GetValue(????);
propertyInfo.PropertyType.GetMethod("Add").Invoke(cln, new object[] { toAdd });
}
}
我遇到的问题是试图将集合从目标中取出,以便我可以调用“Add”方法并添加元素。
关于如何做到这一点的任何想法?
全部^^
【问题讨论】:
-
如果你知道它是一个集合,那么传递 ICollection
会不会比在这里使用反射更好? -
请注意,为了查找
propertyInfo,我可能会使用类似:Type icollectionType = typeof(ICollection<>).MakeGenericType(propertyType); PropertyInfo propertyInfo = target.GetType().GetProperties().FirstOrDefault(o => icollectionType.IsAssignableFrom(o.PropertyType));,而不是简单地查找具有某种类型的泛型参数的类型。
标签: c# reflection collections