c# - 在 "public T SomeMethod<T>(string item) where T : new();"中有 new() 的用例是什么

标签 c# oop generics design-patterns

关闭。这个问题需要更多 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 pagewhere 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/

相关文章:

c# - 同步到异步 - 使同步异步的最佳实践

javascript - 这是子类还是新实例?

javascript - 如何在对象方法上调用requestAnimFrame?

java - CircularLinkedList 删除方法不起作用

java - 覆盖父类的List类型以避免调用方法时进行强制转换

c# - Entity Framework 关系未从数据库加载

javascript - Javascript MVC 的自动操作结果调用

javascript - 如何将 int 列表从 Javascript (Ajax) 发送到 C#?

c# - 调车场算法建模

ios - 如果不应该,则可选绑定(bind)成功