3

在一些现有的代码中,我看到以下内容:

public abstract class BasicComponent<T> : IBasicComponent<T> 
                                          where T : class, new()

我知道抽象类和接口是什么。where T但是当你扩展class和时它在做什么以及发生了什么new()

4

5 回答 5

12

这些是泛型类型约束

class意味着T你使用的必须是一个类(包括接口、委托和数组),new它必须有一个公共的无参数构造函数。

从链接的 MSDN 文档:

其中 T : class - 类型参数必须是引用类型;这也适用于任何类、接口、委托或数组类型。

其中 T : new() - 类型参数必须具有公共无参数构造函数。当与其他约束一起使用时,必须最后指定 new() 约束。

于 2012-08-31T11:37:48.053 回答
1

where T限制泛型类型 T

class意味着 T 必须是一个类并且没有结构或值类型
new意味着 T 必须有无参数构造函数

于 2012-08-31T11:38:30.947 回答
1

Where用于声明对泛型类型参数的约束,这反过来意味着编译器可以允许一些原本不允许的事情,因为它对类型参数知之甚少。

where T : class;

这将类型参数限制T为 aclass -这意味着此方法将仅将其作为值类型或结构接受,class而不是作为值类型或结构接受。

where T : new();

这将类型参数限制为定义T了无参数构造函数的类型因此,编译器可以接受以下内容:

T t = new T();
于 2012-08-31T11:39:56.460 回答
1

它说它T必须是一个引用类型 ( class) 并且必须有一个无参数的构造函数new()

这意味着BasicComponent<T>从它派生的类可以做只能在这种情况下才能做的事情。这也意味着他们可以做其他没有意义的事情。相反,如果我们没有它。

public abstract class BasicComponent<T>
{
  public T Build()
  {
    return new T();//can't do this without `new()` constraint.
  }
  public bool Check(T item)
  {
    return item != null;//only references types can be null, so 
                        //can't do this without `class` constraint
                        //though notice that `default(T)` works for
                        //both reference and value types.
  }
  public bool IsSame(T x, T y)
  {
    return ReferenceEquals(x, y);//pointless with value-types.
                                 //x and y would be passed to IsSame by
                                 //copying, then boxed to two different objects
                                 //then this will always return false.
                                 //as part of a generic implementation that
                                 //accepted both value and reference types
                                 //it might be that we still care to do something
                                 //for reference-equals, in other cases the 
                                 //pointlessness would make the whole class pointless
                                 //for value types.
  }
  public abstract void Whatever();//just added in so the class still does something abstractly!
}

请注意,派生自的类BasicComponent<T>必须至少同样严格 - 它必须具有所有约束BasicComponent<T>,并且可能会或可能不会添加自己的进一步约束。

于 2012-08-31T11:48:16.873 回答
0

T 是您将要使用的通用部分。
关键字在哪里充当过滤器(类似于其他语言)

在这里你已经使用了 class 和 new()

这意味着,
您可以使用要在此泛型类中传递的任何类。
new() 意味着,您正在告诉类它将具有无参数构造函数。

于 2012-08-31T11:42:12.143 回答