关于在c#中使用新约束

时间:2012-01-25 12:41:00

标签: c#

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

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

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

{
}

所以任何人都请让我理解使用新的约束与小&amp;简单的样品供现实世界使用。感谢

5 个答案:

答案 0 :(得分:12)

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

工作示例:

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

现在显然会迫使你为一般参数传递的类型设置一个无参数构造函数:

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

非工作示例:

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
    }
}

答案 1 :(得分:7)

Darin's answer之外,这样的事情会失败,因为Bar没有无参数构造函数

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

   class Foo : ItemFactory<Bar>
   {

   }

   class Bar
   {
      public Bar(int a)
      {

      }
   }

实际错误是:'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();
    }
}

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

答案 2 :(得分:0)

  

新约束指定泛型类声明中的任何类型参数都必须具有公共无参数构造函数。

引自官方website

答案 3 :(得分:0)

您可以阅读new(),就好像它是一个带有构造函数的接口。就像IComparable指定类型T具有方法CompareTo一样,新约束指定类型T具有公共构造函数。

答案 4 :(得分:0)

在您的示例中,约束作用于类声明中的<T>。在第一种情况下,它要求通用T对象具有默认(无参数)构造函数。在第二个示例中,它要求T应该具有默认的无参数构造函数,并且必须实现IComparable接口。