gpt4 book ai didi

c# - 琐事多于真正重要 : Why no new() constraint on Activator. CreateInstance()?

转载 作者:可可西里 更新时间:2023-11-01 08:26:34 24 4
gpt4 key购买 nike

我想有人可以回答这个问题,这是出于好奇而提出的问题:

System.Activator 中的通用 CreateInstance 方法在 .NET v2 中引入,对通用参数没有类型限制,但确实需要激活类型的默认构造函数,否则将抛出 MissingMethodException。对我来说,很明显这个方法应该有一个类型约束,比如

Activator.CreateInstance<T>() where T : new() {
...
}

这里只是一个遗漏还是一些轶事?

更新

如前所述,编译器不允许你这样写

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

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

感谢您查看此内容!

最佳答案

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

// 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>();
}
}

请注意,如果 Activator.CreateInstance<T>有一个where T : new()约束,然后是 Cache<T>上面的类需要那个约束,自Create以来这将是过度限制的。是虚方法,一些派生类可能希望使用不同的实例化方法,例如调用类型的内部构造函数或使用静态构建器方法。

关于c# - 琐事多于真正重要 : Why no new() constraint on Activator. CreateInstance<T>()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5187867/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com