关闭。这个问题需要更多 focused .它目前不接受答案。
想改进这个问题?更新问题,使其仅关注一个问题 editing this post .
7年前关闭。
Improve this question
我正在尝试识别 various uses cases
使用 new()
在声明中
public T SomeMethod<T>(string item) where T : new();
我知道编译器会确保
T
必须有一个默认构造函数。但在所有情况下,这都是有帮助的。我经历过这个link
最佳答案
MSDN's own page在 where T : new()
列出最常见的用例:
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)的。
关于c# - 在 "public T SomeMethod<T>(string item) where T : new();"中有 new() 的用例是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22104297/