如何在c#中为generics类型创建实例
我需要在C#中为通用类创建一个无参数实例。
这该怎么做。
您可以添加: new()
约束:
void Foo() where T : class, new() { T newT = new T(); // do something shiny with newT }
如果您没有约束,那么Activator.CreateInstance
可能会有所帮助(减去编译时检查):
void Foo() { T newT = Activator.CreateInstance (); // do something shiny with newT }
如果你的意思是你自己的类型,那么可能是这样的:
Type itemType = typeof(int); IList list = (IList)Activator.CreateInstance( typeof(List<>).MakeGenericType(itemType));