我有一个容器类,该容器类必须在某个时刻实例化一个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());
}
但是,我对此有多个问题:
Container<SomeForm>.Create<OtherForm>();
,但SomeForm
没有任何影响。我只需要为此助手方法创建一个非泛型(静态)类即可解决此问题。
如果我必须使用一个辅助函数,我希望能够调用Container<MyForm>.Create();
并获取类型为Container<MyForm>
的对象,但这是行不通的,因为我不能为一个非泛型方法,即使它位于一个泛型类中(请参见以下未编译的代码段)。public static Container<TChild> Create()
where TChild : Form, new()
{
return new Container<TChild>(() => TChild());
}
除了我已经提到的以外,还有其他解决方法吗?如果没有,我可以改善解决方法吗?
从第一个代码片段的注释中可以看出,从语义上讲,我希望能够有一个构造器,该构造器通常比类本身具有更多的约束。