繁体   English   中英

如何在c#中为泛型类型创建实例

[英]how to create instance for a generic type in c#

我需要在C#中为通用类创建一个无参数实例。

这个怎么做。

您可以添加: new()约束:

void Foo<T>() where T : class, new() {
    T newT = new T();
    // do something shiny with newT
}

如果您没有约束,那么Activator.CreateInstance<T>可能会有所帮助(减去编译时检查):

void Foo<T>() {
    T newT = Activator.CreateInstance<T>();
    // do something shiny with newT
}

如果你的意思是你自己的类型,那么可能是这样的:

Type itemType = typeof(int);
IList list = (IList)Activator.CreateInstance(
         typeof(List<>).MakeGenericType(itemType));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM