【问题标题】:C# Reflection - Add element to collectionC# 反射 - 将元素添加到集合
【发布时间】: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&lt;&gt;).MakeGenericType(propertyType); PropertyInfo propertyInfo = target.GetType().GetProperties().FirstOrDefault(o =&gt; icollectionType.IsAssignableFrom(o.PropertyType));,而不是简单地查找具有某种类型的泛型参数的类型。

标签: c# reflection collections


【解决方案1】:

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

 object cln = propertyInfo.GetValue(target);

【讨论】:

    猜你喜欢
    • 2014-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-03
    • 1970-01-01
    • 2014-03-29
    • 2017-01-03
    相关资源
    最近更新 更多