更多琐事而不是真正重要:为什么 Activator.CreateInstance() 没有 new() 约束?
我认为有人可能能够回答这个问题,这是出于好奇而提出的问题:
来自 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() 约束的泛型方法的类型参数。在这种情况下,给定的答案似乎是不限制该方法的唯一有效理由......
感谢您查看此内容!
I think there are people who may be able to answer this, this is a question out of curiosity:
The generic CreateInstance
method from System.Activator
, introduced in .NET v2 has no type constraints on the generic argument but does require a default constructor on the activated type, otherwise a MissingMethodException
is thrown. To me it seems obvious that this method should have a type constraint like
Activator.CreateInstance<T>() where T : new() {
...
}
Just an omission or some anecdote lurking here?
Update
As pointed out, the compiler does not allow you to write
private T Create<T>() where T : struct, new()
error CS0451: The 'new()' constraint cannot be used with the 'struct' constraint
However, see comments a struct can be used as type argument to a generic method specifying a new() constraint. Under this circumstance the given answer seems the only valid reason to not constrain the method...
Thanks for looking over this!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我可能是错的,但我认为它的主要好处是它允许您执行以下操作:
请注意,如果
Activator.CreateInstance
有一个where T : new( )
约束,那么上面的Cache
类也需要该约束,这会过于严格,因为Create
是虚拟方法和某些派生类可能希望使用不同的实例化方式,例如调用类型的内部构造函数或使用静态生成器方法。I could be wrong, but the main benefit as I see it is that it allows you to do something like this:
Note that if
Activator.CreateInstance<T>
had awhere T : new()
constraint, then theCache<T>
class above would also need that constraint, which would be overly restrictive sinceCreate
is a virtual method and some derived class might want to use a different means of instantiation, such as calling a type's internal constructor or using a static builder method.