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

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

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

Factory 的泛型约束是允许第一个构造函数的实现所必需的,但它禁止在没有公共(public)默认构造函数的情况下与任何类一起使用。

有没有办法同时允许两者?

最佳答案

不是直接的,但您可以使用非通用的 Factory具有泛型方法的工厂(原文如此),将类型约束放在方法的类型参数上,并使用它来向不受约束的 Factory<T> 提供委托(delegate)类。

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

关于具有 "conditional"约束的 C# 泛型类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9636934/

相关文章:

c# - 如何将存储过程添加到Windows Installer

c# - C++ 和 C# 数组和 Void 转换

c# - 无法运行 MBUnit 单元测试,没有运行按钮/菜单

c# - 单声道上的 Winforms 数据绑定(bind)和 INotifyPropertyChanged

c# - 如何在 C# 中获取传递给 T 的属性类型?

c# - 类型 (x) 参数返回类型 x 的方法

java - 如何获取 java 参数化集合类的类型?

Java 编译器与泛型错误

c# - 有没有办法创建通用的 Action 或 Func

java - 如何动态地将一个类键入为其子类之一