带 Or 的通用类型约束
public T CreateForm<T>() where T: BaseForm, BaseMainForm
我知道上面的意思是T是一个BaseForm
和一个BaseMainForm
。但是是否也可以限制 T 必须是 BaseForm
或 一个 BaseMainForm
?
public T CreateForm<T>() where T: BaseForm, BaseMainForm
I know the above means where T is a BaseForm
and a BaseMainForm
. But is it also possible to make the constraint that T has to be either a BaseForm
or a BaseMainForm
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,这在 C# 中是不允许的。编译器使用泛型约束来确定泛型方法内的
T
上可用的操作 - 因此允许 或 表达式将不是类型安全的。如果您需要此功能,请考虑添加一个涵盖
BaseForm
和BaseMainForm
公共部分的接口,并将其应用为通用约束。这样,接口定义了方法CreateForm
所需的约定 - 并且您必须简单地确保您传入的 Form 实现该接口。像这样的东西:
No, that is not allowed in C#. The compiler uses the generic constraint to determine what operations is available on
T
within the generic method - so allowing an or expression would not be type safe.If you need this, consider adding an interface covering the common parts of
BaseForm
andBaseMainForm
, and apply that as the generic constraint. This way, the interface defines the contract of what the methodCreateForm<T>
needs - and you must simply make sure that the Form's you pass in implement the interface.Something like:
这是不可能的。
考虑添加接口或基类,让这两个类都实现它,并将其用作类型约束。
It's not possible.
Consider adding either an interface or a base class, have both of those classes implement it, and use that as the type constraint.
不,您需要将 CreateForm 感兴趣的 BaseForm 和 BaseMainForm 属性提取到它们都继承自的新接口中,然后您的方法将引用该接口
No, you would need to extract the properties, that CreateForm is interested in, of BaseForm and BaseMainForm into a new interface that they both inherit from and then your method will reference that interface