更重要的琐事:为什么在Activator.CreateInstance <T>()上没有新的()约束?

flq*_*flq 12 .net c# clr base-class-library c#-2.0

我想有些人可能能够回答这个问题,这是一个出于好奇的问题:

.NET v2中引入的泛型CreateInstance方法System.Activator对泛型参数没有类型约束,但在激活类型上需要默认构造函数,否则MissingMethodException抛出a.对我而言,这个方法似乎应该有类型约束

Activator.CreateInstance<T>() where T : new() {
   ...
}
Run Code Online (Sandbox Code Playgroud)

只是遗漏或潜伏在这里的一些轶事?

更新

正如所指出的,编译器不允许你编写

private T Create<T>() where T : struct, new()
error CS0451: The 'new()' constraint cannot be used with the 'struct' constraint
Run Code Online (Sandbox Code Playgroud)

但是,请参阅注释可以将结构用作指定new()约束的泛型方法的类型参数.在这种情况下,给定的答案似乎是不限制方法的唯一正当理由......

谢谢你看看这个!

Dan*_*Tao 8

我可能是错的,但我认为它的主要好处是它允许你做这样的事情:

// Simple illustration only, not claiming this is awesome code!
class Cache<T>
{
    private T _instance;

    public T Get()
    {
        if (_instance == null)
        {
            _instance = Create();
        }

        return _instance;
    }

    protected virtual T Create()
    {
        return Activator.CreateInstance<T>();
    }
}
Run Code Online (Sandbox Code Playgroud)

注意,如果Activator.CreateInstance<T>有一个where T : new()约束,那么Cache<T>上面的类需要这个约束,这将Create是一个过于严格的限制,因为它是一个虚方法,一些派生类可能想要使用不同的实例化方法,如调用类型的内部构造函数或使用静态构建器方法.

  • @Dan,LukeH:对于它的价值,对`new T()`的调用实际上变成了对'Activator.CreateInstance <T>()`的调用. (2认同)