如何以编程对象转换在运行时?对象

2023-09-07 00:43:00 作者:不暗的黑夜

假设我有一样的自定义控件:

Suppose I have a custom control like:

MyControl : Control

如果我有code是这样的:

if I have code like this:

List<Control> list = new ...
list.Add (myControl);

RolloutAnimation anim = list[0];

我知道我可以在编译时做,但我想这样做在运行时和访问MyControl特定的功能。

I know I can do it at compile time but I wanna do it at runtime and access MyControl specific functionality.

推荐答案

你为什么要在运行时做呢?如果您有更多类型的列表控件中,有一些特定的功能,但不同类型的,或许他们应该实现一个共同的接口:

Why do you want to do it at runtime? If you have more types of Controls in your List, that have some specific functionality, but different types, perhaps they should implement a common interface:

interface MyControlInterface
{
    void MyControlMethod();
}

class MyControl : Control, MyControlInterface
{
    // Explicit interface member implementation:
    void MyControlInterface.MyControlMethod()
    {
        // Method implementation.
    }
}

class MyOtherControl : Control, MyControlInterface
{
    // Explicit interface member implementation:
    void MyControlInterface.MyControlMethod()
    {
        // Method implementation.
    }
}


.....

//Two instances of two Control classes, both implementing MyControlInterface
MyControlInterface myControl = new MyControl();
MyControlInterface myOtherControl = new MyOtherControl();

//Declare the list as List<MyControlInterface>
List<MyControlInterface> list = new List<MyControlInterface>();
//Add both controls
list.Add (myControl);
list.Add (myOtherControl);

//You can call the method on both of them without casting
list[0].MyControlMethod();
list[1].MyControlMethod();
 
精彩推荐
图片推荐