具有"条件"约束的C#泛型类?

Jon*_*ric 3 c# generics

class Factory<Product> where Product : new()
{
    public Factory()
        : this(() => new Product())
    {
    }

    public Factory(System.Func<Product> build)
    {
        this.build = build;
    }

    public Product Build()
    {
        return build();
    }

    private System.Func<Product> build;
}
Run Code Online (Sandbox Code Playgroud)

Factory,当Product有一个公共默认构造函数时,我希望客户端不必指定如何构造一个(通过第一个构造函数).但是,我想允许Product没有公共默认构造函数的情况(通过第二个构造函数).

Factory需要通用约束来允许第一个构造函数的实现,但它禁止在没有公共默认构造函数的情况下使用任何类.

有没有办法允许两者?

Jon*_*eet 8

不是直接的,但你可以使用非通用Factory工厂(原文如此)与通用方法,把类型约束上的类型参数的方法,并用它来委托提供给不受约束Factory<T>类.

static class Factory
{
    public static Factory<T> FromConstructor<T>() where T : new()
    {
        return new Factory<T>(() => new T());
    }
}

class Factory<TProduct>
{
    public Factory(Func<TProduct> build)
    {
        this.build = build;
    }

    public TProduct Build()
    {
        return build();
    }

    private Func<TProduct> build;
}
Run Code Online (Sandbox Code Playgroud)