如何在C#泛型类型创建实例 [英] how to create instance for a generic type in c#
本文介绍了如何在C#泛型类型创建实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要建立在C#泛型类的参数实例。
I need to create an parameterless instance for a Generic Class in C#.
如何做到这一点。
推荐答案
您可以添加:新的()
约束:
void Foo<T>() where T : class, new() {
T newT = new T();
// do something shiny with newT
}
如果你不这样做有约束,则 Activator.CreateInstance< T>
可以帮助(减去编译时检查):
If you don't have the constraint, then Activator.CreateInstance<T>
may help (minus the compile-time checking):
void Foo<T>() {
T newT = Activator.CreateInstance<T>();
// do something shiny with newT
}
如果你的意思是你的类型本身,那么很可能是这样的:
If you mean you the type itself, then probably something like:
Type itemType = typeof(int);
IList list = (IList)Activator.CreateInstance(
typeof(List<>).MakeGenericType(itemType));
这篇关于如何在C#泛型类型创建实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文