带 Or 的通用类型约束

发布于 2024-11-25 01:47:20 字数 265 浏览 1 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

紧拥背影 2024-12-02 01:47:20

不,这在 C# 中是不允许的。编译器使用泛型约束来确定泛型方法内的 T 上可用的操作 - 因此允许 表达式将不是类型安全的。

如果您需要此功能,请考虑添加一个涵盖 BaseFormBaseMainForm 公共部分的接口,并将其应用为通用约束。这样,接口定义了方法 CreateForm 所需的约定 - 并且您必须简单地确保您传入的 Form 实现该接口。

像这样的东西:

public interface IBaseForm 
{
    Foo();
}

class BaseForm : IBaseForm {}
class BaseMainForm : IBaseForm {}

public T CreateForm<T>() where T : IBaseForm

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 and BaseMainForm, and apply that as the generic constraint. This way, the interface defines the contract of what the method CreateForm<T> needs - and you must simply make sure that the Form's you pass in implement the interface.

Something like:

public interface IBaseForm 
{
    Foo();
}

class BaseForm : IBaseForm {}
class BaseMainForm : IBaseForm {}

public T CreateForm<T>() where T : IBaseForm
七度光 2024-12-02 01:47:20

这是不可能的。

考虑添加接口或基类,让这两个类都实现它,并将其用作类型约束。

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.

揪着可爱 2024-12-02 01:47:20

不,您需要将 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文