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

Joa*_*nge 0 .net c# casting winforms

假设我有一个自定义控件,如:

MyControl : Control
Run Code Online (Sandbox Code Playgroud)

如果我有这样的代码:

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

RolloutAnimation anim = list[0];
Run Code Online (Sandbox Code Playgroud)

我知道我可以在编译时完成它,但我想在运行时执行它并访问MyControl特定的功能.

luv*_*ere 9

为什么要在运行时执行此操作?如果列表中有更多类型的控件,它们具有某些特定功能,但具有不同类型,那么它们可能应该实现一个通用接口:

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();
Run Code Online (Sandbox Code Playgroud)