对泛型类的构造函数的泛型约束

时间:2019-12-13 14:34:49

标签: c# generics

我有一个容器类,该容器类必须在某个时刻实例化一个Form。 90%的时间,表单将具有无参数的构造函数。因此,将通用参数约束为new()很方便,因此您可以直接实例化它。 但是,我还希望能够传入一个工厂方法,该方法可以在需要一些参数的情况下为我创建表单。当然,这最后一点意味着我不能将泛型类型限制为new()

class Container<TChild>
    where TChild : Form, new() // <-- this new() constraint should go away (Form would stay)
{
    private readonly Func<TChild> _createChild;

    public Container()
        // where TChild : Form, new() <-- this is what I want instead of the class-wide new()-constraint but that doesn't compile
    {
        _createChild = () => new TChild();
    }

    public Container(Func<TChild> createChild)
    {
        _createChild = createChild;
    }

    public void ShowChild()
    {
        _createChild().Show(); // you could substitute the Form-contraint with whatever you like and act accordingly here
    }
}

在不使用第二类的情况下(我想避免),我唯一的想法是在new()情况下使用静态帮助函数。

public static Container<TParamlessChild> Create<TParamlessChild>()
    where TParamlessChild : Form, new()
{
    return new Container<TParamlessChild>(() => new TParamlessChild());
}

但是,我对此有多个问题:

  1. 在我的用例中,因为几乎所有我要使用的子代都有无参数构造函数,所以我有90%的时间会使用它。由于我的静态帮助器函数中的泛型类型比类的泛型类型只能具有更多的约束,因此我也无法解决任何问题。我不喜欢提供辅助函数来实例化一个类型的简单对象,但对于提供更复杂类型的对象却不愿意,这正是无参数构造函数的目的。
  2. 我必须指定一个完全无用且不相关的通用参数,以便甚至可以访问静态函数。 Container<SomeForm>.Create<OtherForm>();,但SomeForm没有任何影响。我只需要为此助手方法创建一个非泛型(静态)类即可解决此问题。 如果我必须使用一个辅助函数,我希望能够调用Container<MyForm>.Create();并获取类型为Container<MyForm>的对象,但这是行不通的,因为我不能为一个非泛型方法,即使它位于一个泛型类中(请参见以下未编译的代码段)。
public static Container<TChild> Create()
    where TChild : Form, new()
{
    return new Container<TChild>(() => TChild());
}

除了我已经提到的以外,还有其他解决方法吗?如果没有,我可以改善解决方法吗?
从第一个代码片段的注释中可以看出,从语义上讲,我希望能够有一个构造器,该构造器通常比类本身具有更多的约束。

0 个答案:

没有答案
相关问题