从 winforms 基类显式调用接口方法

发布于 2025-01-03 19:24:50 字数 720 浏览 2 评论 0原文

我有一个 winforms 基本表单,其中包含对需要以派生形式实现的某些方法的调用。我想确保我的派生形式确实实现了这些方法并提供尽可能多的编译时支持。我们都知道如果您希望能够使用设计器,则无法将 winforms 类定义为抽象类的问题(请参阅 这个问题)。

我创建了一个接口,其中包含需要以派生形式实现的方法签名。然后,我直接从基类调用 Interface 方法,如下所示:(

((IMyFormInterface)this).SomeInterfaceMethod();

请注意,我的基类没有继承 IMyFormInterface。如果继承了,则派生类不会被迫实现它。)

并且然后我以派生形式继承接口(编译器强制我实现):

public partial class TestForm : BaseForm, IMyFormInterface

我(或其他用户)唯一需要记住的是继承IMyFormInterface

这样直接调用接口方法可以吗?我所有这一切的目标是能够尽可能接近确保派生表单在编译时而不是运行时实现这些“抽象”表单方法。

I have a winforms baseform that contain calls to certain methods that need to be implemented in derived forms. I want to ensure that my derived forms do indeed implement those methods with as much compile time support as possible. We all know the problem of not being able to define a winforms class as abstract if you want to be able to use the designer (see this question).

I created an Interface that contains the method signatures that need to be implemented in a derived form. I then call the Interface methods directly from the base class like such:

((IMyFormInterface)this).SomeInterfaceMethod();

(Note that my base class does not inherit IMyFormInterface. If it did, then derived classes wouldn't be forced to implement it.)

And then I inherit from the Interface in my derived form (which the compiler forces me to implement):

public partial class TestForm : BaseForm, IMyFormInterface

The only thing I (or other users) have to remember is to inherit IMyFormInterface.

Is it acceptable to call interface methods directly like this? My goal in all of this is to be able to get as close as possible to ensuring derived forms implement these "abstract" form methods at compile time, not run time.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

-黛色若梦 2025-01-10 19:24:50

这是解决设计者限制的一种方法。另一种方法是使用设计器构建一个UserControl,然后让您的表单基类抽象化并实例化停靠到整个客户端区域的控件。

如果您使用这种方法,我会在构造函数中断言 (this is IMyFormInterface) 以尽早捕获该错误。

That's one way to work around the designer restriction. Another would be to use the designer to build a UserControl, and then let your form base class be abstract and instantiate the control docked to the full client area.

If you use this approach, I'd assert (this is IMyFormInterface) in your constructor to catch that error as early as possible.

咋地 2025-01-10 19:24:50

我的基本控件也有同样的问题。
因为 Designer 不喜欢抽象基控制类,所以我将抽象方法重构为抛出 NotImplementedException 的虚拟方法。
我不知道哪种方式最好。

I had the same problem with a base control.
Because Designer does not like abstract base control classes I refactored the abstract methods to virtual methods that throw a NotImplementedException.
I don't know which way is the best.

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