【问题标题】:What's the benefits of using the method which is using "new()" over the one not using "new()" with where clause in the method in c#? [duplicate]使用“new()”的方法比不使用“new()”的方法和 C# 方法中的 where 子句有什么好处? [复制]
【发布时间】:2019-03-26 06:08:46
【问题描述】:

有两种方法可以完成相同的任务。它们的唯一区别是一个有“new()”而另一个没有。

方法有:

方法一

public void Method1<T>(BaseReportContent content) where T : BaseReportContent, new()
{
   //Codes
}

方法二

public void Method2<T>(BaseReportContent content) where T : BaseReportContent
{
   //Codes
}

使用一个比另一个有什么好处?

如果需要更多信息以使这个问题更准确,请告诉我。

【问题讨论】:

标签: c# methods


【解决方案1】:

new() 约束将允许您创建一个新的T。比如

public void Method1<T>(BaseReportContent content) where T : BaseReportContent, new()
{
    var myT = new T();
}

注意:有一些注意事项

new constraint (C# Reference)

新约束指定泛型类中的任何类型参数 声明必须有一个公共的无参数构造函数。要使用 新约束,类型不能是抽象的。


其他资源

您可以在此处找到有关通用约束的更多信息

Constraints on type parameters (C# Programming Guide)

约束通知编译器类型参数的能力 一定有。没有任何约束,类型参数可以是任何 类型。编译器只能假设 System.Object 的成员,其中 是任何 .NET 类型的最终基类。了解更多信息, 请参阅为什么使用约束。如果客户端代码尝试实例化您的 通过使用约束不允许的类型进行类,结果 是编译时错误。使用 where 指定约束 上下文关键字。下表列出了七种类型 约束:

最后,如果你需要创建一些需要构造函数参数的东西,你可以使用

Activator.CreateInstance Method

使用构造函数创建指定类型的实例 与指定参数最匹配。

【讨论】:

    【解决方案2】:

    第一种方法使用new constaint,表示可以写:

    public void Method1<T>(BaseReportContent content) where T : BaseReportContent, new()
    {
        var foo = new T();
    }
    

    第二种方法没有这个约束,也就是说你不能写这样的代码。

    【讨论】:

      猜你喜欢
      • 2011-11-03
      • 2023-02-08
      • 1970-01-01
      • 2016-03-27
      • 1970-01-01
      • 1970-01-01
      • 2021-05-03
      • 1970-01-01
      • 2016-03-06
      相关资源
      最近更新 更多