[英]Instantiate generic c# List when the reflected type itself is a List
I have a reflected Type, which ends up being a List<Type>
. 我有一个反映的类型,最终是一个
List<Type>
。 So I have: 所以我有:
Type modelType = GetMyType();
So - modelType
could be List<ClassA>
or List<ClassB>
, etc. depending on the situation. 所以 -
modelType
可以是List<ClassA>
或List<ClassB>
等,具体取决于具体情况。
How do I create this type, and then populate it? 如何创建此类型,然后填充它?
I know I can do this: 我知道我可以这样做:
var myList = Activator.CreateInstance(modelType);
But then how do I add items to it, which I would normally do with myList.Add(new ClassA())
or myList.Add(new ClassB())
knowing that I don't really know the ClassA
or ClassB
type - I just know that modelType is List<ClassA>
- Is there some other way I should be instantiating it so that I can add items to it? 但是我如何添加项目,我通常会使用
myList.Add(new ClassA())
或myList.Add(new ClassB())
知道我不知道ClassA
或ClassB
类型 - 我只知道modelType是List<ClassA>
- 是否有其他方法我应该实例化它以便我可以添加项目?
Have a look at this example, it uses the Type.GetGenericArguments Method to retrieve the lists inner type. 看看这个例子,它使用Type.GetGenericArguments方法来检索列表内部类型。 Then proceed with reflection as usual.
然后照常进行反射。
static void Main(string[] args)
{
Type modelType = GetMyType();
var myList = Activator.CreateInstance(modelType);
var listInnerType = modelType.GetGenericArguments()[0];
var listInnerTypeObject = Activator.CreateInstance(listInnerType);
var addMethod = modelType.GetMethod("Add");
addMethod.Invoke(myList, new[] { listInnerTypeObject });
}
static Type GetMyType()
{
return typeof(List<>).MakeGenericType((new Random().Next(2) == 0) ? typeof(A) : typeof(B));
}
class A { }
class B { }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.