簡體   English   中英

將項添加到通用列表 <T> 與反思

[英]Adding an item to a generic List<T> with Reflection

編輯:請繼續前進,沒有什么可看的。

這個問題的解決方案與Reflection沒有任何關系,與我無關,沒有注意基類中集合屬性的實現。


我正在嘗試使用Reflection使用以下方法將項添加到集合中:

public void AddReferenceToCollection(object targetResource, string propertyName, object resourceToBeAdded)
{
    Type targetResourceType = targetResource.GetType();
    PropertyInfo collectionPropertyInfo = targetResourceType.GetProperty(propertyName);

    // This seems to get a copy of the collection property and not a reference to the actual property
    object collectionPropertyObject = collectionPropertyInfo.GetValue(targetResource, null);
    Type collectionPropertyType = collectionPropertyObject.GetType();
    MethodInfo addMethod = collectionPropertyType.GetMethod("Add");

    if (addMethod != null)
    {
        // The following works correctly (there is now one more item in the collection), but collectionPropertyObject.Count != targetResource.propertyName.Count
        collectionPropertyType.InvokeMember("Add", System.Reflection.BindingFlags.InvokeMethod, null, collectionPropertyObject, new[] { resourceToBeAdded });
    }
    else
    {
        throw new NotImplementedException(propertyName + " has no 'Add' method");
    }
}

但是,似乎調用targetResource.GetType().GetProperty(propertyName).GetValue(targetResource, null)返回targetResource.propertyName的副本而不是對它的引用,因此對collectionPropertyType.InvokeMember的后續調用會影響副本而不是參考。

如何將resourceToBeAdded對象添加到targetResource對象的propertyName集合屬性中?

嘗試這個:

public void AddReferenceToCollection(object targetResource, string propertyName, object resourceToBeAdded)
{
    var col = targetResource.GetType().GetProperty(propertyName).GetValue(targetResource, null) as IList;
    if(col != null)
        col.Add(resourceToBeAdded);
    else
        throw new InvalidOperationException("Not a list");
}

編輯 :測試用法

void Main()
{

    var t = new Test();
    t.Items.Count.Dump(); //Gives 1
    AddReferenceToCollection(t, "Items", "testItem");
    t.Items.Count.Dump(); //Gives 2
}
public class Test
{
    public IList<string> Items { get; set; }

    public Test()
    {
        Items = new List<string>();
        Items.Add("ITem");
    }
}

暫無
暫無

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

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