泛型:何时使用new()作为类型参数的约束?

CSh*_*oob 3 c# generics

type参数必须具有公共无参数构造函数.与其他约束一起使用时,必须最后指定new()约束.

当需要这种约束时,你能给我一个示例场景吗?

sta*_*ica 9

这基本上是new()约束归结为:

class Factory<T> where T : new()
{
    public T Create()
    {
        return new T();
        //     ^^^^^^^
        //     this requires the new() type constraint.
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,您不允许将参数传递给构造函数.如果你想初始化新的对象,你可以通过引入另一个约束来实现这个目的:

interface ILikeBananas
{
    double GreenBananaPreferenceFactor { get; set; }
}

class Factory<T> where T : ILikeBananas, new()
{
    public T Create(double greenBananaPreferenceFactor)
    {
        ILikeBananas result = new T();
        result.GreenBananaPreferenceFactor = greenBananaPreferenceFactor;

        return (T)result;
        //     ^^^^^^^^^
        //     freely converting between ILikeBananas and T is permitted
        //     only because of the interface constraint.
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,实例化对象的另一种方法是via Activator.CreateInstance,它为您提供了更多自由,例如将参数直接传递给构造函数.

Activator.CreateInstance并不严格要求new()约束; 但是,实例化的类型仍然需要提供合适的构造函数.