如何添加到C#反射列表? [重复]

问题描述 投票:-1回答:1

这个问题已经在这里有一个答案:

因为我通过迭代一个通用对象的属性,我可以找到一个List<T>

到目前为止,我已经能够初始化列表中,但我似乎无法得到如何获取列表类型,初始化对象,放入数据,最后添加到列表中?

下面的代码,并在那里我卡住了:

private static void FillMePlease<T>(T genericThingy)
{
    foreach (PropertyInfo propertyInfo in genericThingy.GetType().GetProperties())
    {
        if (propertyInfo.PropertyType == typeof(string))
        {
            propertyInfo.SetValue(genericThingy, "Test", null);
        }
        else
        {
            //var list = Activator.CreateInstance(propertyInfo.PropertyType);
            //Now I'm stumped.
        }
    }
}
c# reflection collections
1个回答
3
投票

我不能完全肯定你的问题的不同位如何结合在一起的,所以这里有一些希望的指针。

要看到一个类型是List<T>

type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>)

为了获得在TList<T>

elementType = type.GetGenericArguments()[0]

为了构建一个List<T>的,只给出了T类型:

typeof(List<>).MakeGenericType(elementType)

要使用反射的项目添加到List<T>

var methodInfo = type.GetMethod("Add");
methodInfo.Invoke(list, new object[] { itemToAdd });
© www.soinside.com 2019 - 2024. All rights reserved.