C#Reflection - 将元素添加到集合中

时间:2015-03-10 12:38:25

标签: c# reflection collections

我有一种方法试图找到一个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 });
        }
    }

我遇到的问题是试图从目标中取出集合,以便我可以调用&#34;添加&#34;方法并添加元素。

关于如何做到这一点的任何想法?

ty all ^^

1 个答案:

答案 0 :(得分:1)

你想从目标中获取当前值,如果是,那么。

 object cln = propertyInfo.GetValue(target);
相关问题