C# 反射 - 将元素添加到集合
C# Reflection - Add element to collection
我有一个方法试图找到对象中存在的 Hash<> 类型集合并向该集合添加新元素。现在我有以下片段:
/// <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" 方法并添加元素。
知道怎么做吗?
全部^^
您想从目标中获取当前值,如果是的话。
object cln = propertyInfo.GetValue(target);
我有一个方法试图找到对象中存在的 Hash<> 类型集合并向该集合添加新元素。现在我有以下片段:
/// <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" 方法并添加元素。
知道怎么做吗?
全部^^
您想从目标中获取当前值,如果是的话。
object cln = propertyInfo.GetValue(target);