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

时间:2009-12-01 23:10:36

标签: c# .net winforms casting

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

MyControl : Control

如果我有这样的代码:

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

RolloutAnimation anim = list[0];

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

4 个答案:

答案 0 :(得分: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();

答案 1 :(得分:4)

((MyControl)list[0]).SomeFunction()

答案 2 :(得分:1)

(MyControl)list[0]将返回MyControl类型的对象,如果list [0]不是MyControl,则抛出错误。

list[0] as MyControl将返回MyControl类型的对象,如果list [0]不是MyControl类型,则返回null

您还可以检查列表[0]测试list[0] is MyControl

的类型类型

答案 3 :(得分:0)

MyControl my_ctrl = list[0] as MyControl;

if(my_ctrl != null)
{
  my_ctrl.SomeFunction();
}

// Or

if(list[0] is MyControl)
{
  ((MyControl)list[0]).SomeFunction();
}