如何声明"控制实现接口ISomething"类型的变量/参数?

Ror*_*ker 1 c# vb.net controls interface winforms

我希望以这样一种方式声明一个变量,因为它只能分配从Control派生的值并实现ISomething接口.

我打算将ISomething接口添加到控件的衍生物中.

我想从TextBox和DatePicker派生SpecialTextBox和SpecialDatePicker,并在每个上实现ISomething接口.

我希望能够将这些控件中的每一个分配给一个类型为"Control也实现ISomething"的变量,这样就可以从那里调用它们的ISomething方法,或者可以将它们添加到窗体上的控件集合中.

所以....如何声明类型"Control也实现ISomething"的变量

理想情况下,答案是VB.Net,但我也会对C#方法感兴趣.

Mar*_*ell 10

一种方法是使用泛型 - 即通用方法:

void Foo<T>(T control) where T : Control, ISomething
{
    // use "control"
    // (you have access to all the Control and ISomething members)
}
Run Code Online (Sandbox Code Playgroud)

现在,您可以拨打美孚带有在其他变量Control实现ISomething-你不需要指定通用的,但:

Foo(someName);
Run Code Online (Sandbox Code Playgroud)

是你所需要的全部.如果你给它的东西不是一个ControlISomething,编译器会告诉你.


更新:我不"做"VB,但反射器告诉我,上面翻译为:

Private Sub Foo(Of T As { Control, ISomething })(ByVal control As T)

End Sub
Run Code Online (Sandbox Code Playgroud)