簡體   English   中英

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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM