简体   繁体   English

VB.NET WinForms实现接口

[英]VB.NET WinForms implementing an interface

VB.NET VB.NET

I want some WinForms to implement an interface, and be able to pass these to a procedure which can 'see' the implemented properties as well as the 'standard methods' of a Form. 我希望一些WinForms实现一个接口,并能够将它们传递给可以“查看”表单的已实现属性以及“标准方法”的过程。 This is what I have so far... 这是我到目前为止所拥有的...

Public Interface IMyInterface

    Property MyProperty As String

End Interface

Public Class MyForm

    Implements IMyInterface

    Private _MyProperty As String

    Public Property MyProperty() As String Implements IMyInterface.MyProperty
    Get
        Return _MyProperty
    End Get
    Set(ByVal value As String)
        _MyProperty = value
    End Set

End Property

End Class

then, elsewhere I have my method as follows... 然后,在其他地方,我的方法如下...

Public Sub DoSomething(MyForm As IMyInterface)

    MyForm.MyProperty = "x"
    MyForm.ShowDialog()

End Sub

The obvious problem is that the compiler doesn't know what .ShowDialog is, and if I pass my form in as 'MyForm As Form' it doesn't know what 'MyProperty' is. 明显的问题是编译器不知道.ShowDialog是什么,并且如果我以“ MyForm As Form”形式传递表单,则它也不知道“ MyProperty”是什么。 I understand the reasons for this, but not how to solve this problem. 我了解原因,但不了解如何解决此问题。 Is a simple casting to Form the correct way to address this? 一个简单的铸造形成正确的方法来解决这个问题?

Many thanks. 非常感谢。

You need to inherit System.Windows.Forms.Form to gain all regular form functionality and then Implement IMyInterface . 您需要继承System.Windows.Forms.Form以获得所有常规表单功能,然后实现IMyInterface

Public Class MyForm
    Inherits System.Windows.Forms.Form
    Implements IMyInterface

Passing MyForm As IMyInterface into the DoSomething() method is fine, however to use the regular form methods you'll need to cast it. MyForm As IMyInterface传递到DoSomething()方法中很好,但是,要使用常规表单方法,则需要对其进行强制转换。 Alternatively you could pass in the Form and then cast to IMyInterface , your choice. 另外,您可以传递Form ,然后将其转换为IMyInterface ,这是您的选择。

Public Sub DoSomething(MyIForm As IMyInterface)
        MyIForm.MyProperty = "x"

        Dim MyForm As Form = TryCast(MyIForm, Form)
        MyForm.ShowDialog()

Another aproach can be using your own base class 另一个方法可以使用您自己的基类

Public Class MyBaseForm
    Inherits System.Windows.Forms.Form

    Public Property MyProperty As String

End Class

Then all your forms can inherit that base form 然后,您所有的表单都可以继承该基本表单

Public Class MyForm
    Inherits MyBaseForm

End Class

And you can use property and standard method of System.Windows.Forms.Form without casting 而且您可以使用System.Windows.Forms.Form属性和标准方法,而无需强制转换

Public Sub DoSomething(someform As MyForm)
    someform.MyProperty = "Some value"
    someform.ShowDialog()
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM