C # generic class with conditional constraint?

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

      

In Factory

when it Product

has a public default constructor, I would like clients not to have to tell how to build it (via the first constructor). However, I would like to resolve situations where Product

there is no default public constructor (via the second constructor).

Factory

A general constraint is required to allow the first constructor to be implemented, but it disallows use with any class without a public default constructor.

Is there a way to resolve both?

+3


source to share


1 answer


Not directly, but you can use a non-generic Factory

factory (sic) with a generic method, put a type constraint in the type parameter for the method, and use that to provide the delegate with unlimited 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;
}

      

+8


source







All Articles