.net 2.0 中的泛型:在 class 定义中使用 Where class

Generics in .net 2.0 : Using a Where class on a class definition

在 "Programing in C#" this 书的 objective 2.1 中的认证准备期间,其中针对泛型类型显示了以下代码:

class MyClass<T> where T : class, new()
{
    public MyClass()
    {
        MyProperty = new T();
    }

    T MyProperty { get; set; }
}

我知道泛型类型是什么以及我们为什么需要它,但是任何人都可以解释这个令人困惑的代码以及我们如何在任何示例中使用它。

我猜你不明白这部分:

where T:class,new()

这表示 T 必须是引用类型(即 class)并且它必须具有默认构造函数(不带参数的构造函数)。这意味着 T 不能是 int 因为它是一个结构。它也不能是 StreamReader 因为它没有默认构造函数。

为什么这有用?

有些东西只能与引用类型一起使用,而不能与值类型一起使用,例如as。因为你说 T 必须有一个默认构造函数,你可以这样做:

public MyClass()
{
    MyProperty = new T();
}
T MyProperty { get; set; }

因为T必须有一个默认的构造函数,你可以调用new T().