public T SomeMethod< T>(string item)中的new()的用例是T:new();“ [英] What are the use cases of having new() in "public T SomeMethod<T>(string item) where T : new();"
本文介绍了public T SomeMethod< T>(string item)中的new()的用例是T:new();“的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试识别各种用例
在 new()
中使用
I am trying to identify various uses cases
of using new()
in statement
public T SomeMethod<T>(string item) where T : new();
我知道编译器将确保 T
必须有一个默认构造函数。但是在所有情况下都是有帮助的。
I know compiler will ensure that T
must have a default constructor. But in what all scenario this is helpful.
我已经经历了这个链接
推荐答案
MSDN自己的页面在其中T:new()
列出最常见的用法case:
MSDN's own page on where T : new()
lists the most common use case:
当您的通用类创建新的类型实例时,将新约束应用于类型参数,如以下示例所示:
Apply the new constraint to a type parameter when your generic class creates new instances of the type, as shown in the following example:
class ItemFactory<T> where T : new()
{
public T GetNewItem()
{
return new T();
}
}
约束还要求无参数构造函数为> public 。
The constraint also requires that the parameterless constructor be public.
这篇关于public T SomeMethod< T>(string item)中的new()的用例是T:new();“的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文