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

San*_*osh 3 c# generics

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

这该怎么做.

Mar*_*ell 21

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

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

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

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

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

Type itemType = typeof(int);
IList list = (IList)Activator.CreateInstance(
         typeof(List<>).MakeGenericType(itemType));
Run Code Online (Sandbox Code Playgroud)

  • 跟进安德鲁的观点; `:new()`约束允许在你点击"build"时调用代码进行健全性检查,但实际上它归结为相同的IL(对于各种实现细节).没有它它会工作正常,但如果你调用`Foo <string>`,那么期待痛苦. (2认同)