关于在c#中使用新约束

Tho*_*mas 13 c#

我从不使用新约束,因为我不清楚使用它.在这里,我发现了一个样本,但我只是不明白使用.这是代码

class ItemFactory<T> where T : new()
{
    public T GetNewItem()
    {
        return new T();
    }
}

public class ItemFactory2<T> where T : IComparable, new()

{
}
Run Code Online (Sandbox Code Playgroud)

所以任何人都请让我理解使用新的Constraint与小而简单的样品,以供现实世界使用.谢谢

Dar*_*rov 12

此约束要求使用的泛型类型是非抽象的,并且它具有允许您调用它的默认(无参数)构造函数.

工作范例:

class ItemFactory<T> where T : new()
{
    public T GetNewItem()
    {
        return new T();
    }
}
Run Code Online (Sandbox Code Playgroud)

现在显然会强制你为一个参数传递的类型有一个无参数构造函数:

var factory1 = new ItemFactory<Guid>(); // OK
var factory2 = new ItemFactory<FileInfo>(); // doesn't compile because FileInfo doesn't have a default constructor
var factory3 = new ItemFactory<Stream>(); // doesn't compile because Stream is an abstract class
Run Code Online (Sandbox Code Playgroud)

非工作示例:

class ItemFactory<T>
{
    public T GetNewItem()
    {
        return new T(); // error here => you cannot call the constructor because you don't know if T possess such constructor
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @Novakov:你部分正确:如果你的类本身没有定义构造函数,编译器会生成一个没有参数的构造函数,什么也不做,并调用基类的默认构造函数.那是对的.但是,术语"默认构造函数"表示(1)公共和(2)没有参数的所有构造函数. (4认同)
  • @Novakov:不对.默认的ctor是没有参数的ctor.但它的身体不需要是空的,它可以包含代码. (3认同)
  • @Daniel:很高兴知道,谢谢你的解释 (2认同)

SwD*_*n81 7

除了Darin的答案之外,这样的事情会因为Bar没有无参数构造函数而失败

   class ItemFactory<T> where T : new()
   {
      public T GetNewItem()
      {
         return new T();
      }
   }

   class Foo : ItemFactory<Bar>
   {

   }

   class Bar
   {
      public Bar(int a)
      {

      }
   }
Run Code Online (Sandbox Code Playgroud)

实际错误是: 'Bar' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'ItemFactory<T>'

以下也会失败:

class ItemFactory<T>
{
    public T GetNewItem()
    {
        return new T();
    }
}
Run Code Online (Sandbox Code Playgroud)

实际错误是: Cannot create an instance of the variable type 'T' because it does not have the new() constraint