[英]C# Reflection - Add element to collection
I have a method that tries to find a Hash<> type collection that exists in an object and add a new element to that collection. 我有一个方法试图找到对象中存在的Hash <>类型集合,并向该集合添加新元素。 Right now I have the following snippet: 现在,我有以下片段:
/// <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 });
}
}
The problem I'm having is trying to get the collection out of the target so I can invoke the "Add" method and add the element. 我遇到的问题是试图使集合脱离目标,因此我可以调用“ Add”方法并添加元素。
Any ideia on how to do this? 关于如何执行此操作的任何想法?
ty all ^^ 全部^^
您想要从目标获取当前值,如果是这样的话。
object cln = propertyInfo.GetValue(target);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.