我怎样才能得到一个带有反射的通用列表的实例?

How can I get a instance of a generic list with reflection?

我现在不知道如何获取 Invoke 的参数实例(请参阅示例变量 "listInstance")。 我不想创建一个新列表(使用 Activator.CreateInstance),我想向现有列表实例添加一个对象。 如何获取对象 Sample.Samples?

using System.Collections.Generic;

public class Class<T>
{
  public readonly IList<T> InternalList = new List<T>();
  public virtual void Add(T obj)
  {
    InternalList.Add(obj);
  }
}
public class Sample
{
  public Class<Sample> Samples { get; set; } = new Class<Sample>();
}

class Program
{
  static void Main(string[] args)
  {
    var cla = new Sample();
    var propertyInfo = cla.GetType().GetProperty("Samples");
    var newSample = new Sample();
    var addMethod = propertyInfo.PropertyType.GetMethod("Add");

    var listInstance = ???; // Instance of the Property Sample.Samples

    addMethod.Invoke(listInstance, new[] { newSample });
  }
}

获取 属性 的值并对其调用“添加”方法:

class Program
{
    static void Main(string[] args)
    {
        var cla = new Sample();
        var propertyInfo = cla.GetType().GetProperty("Samples");
        var addMethod = propertyInfo.PropertyType.GetMethod("Add");
        var samples = propertyInfo.GetValue(cla); // retrieve property value
        var newSample = new Sample();

        addMethod.Invoke(samples, new[] { newSample });
    }
}
var listInstance = (Class<Sample>)propertyInfo.GetValue(clr)

您可以直接将其转换为预期的类型,因此您无需使用反射调用方法。

我认为这应该可行:

PropertyInfo propInfo = newSample.GetType().GetProperty("Samples"); //this returns null
var samples = propInfo.GetValue(newSample, null);