How to cast an object programmatically at runtime?

Deadly 提交于 2020-01-17 03:43:26

问题


Suppose I have a custom control like:

MyControl : Control

if I have code like this:

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

RolloutAnimation anim = list[0];

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


回答1:


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();



回答2:


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



回答3:


(MyControl)list[0] will return an object of type MyControl, or throw error if list[0] is not a MyControl.

list[0] as MyControl will return an object of type MyControl, or null if list[0] is not of type MyControl

You can also check type type of list[0] testing list[0] is MyControl




回答4:


MyControl my_ctrl = list[0] as MyControl;

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

// Or

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


来源:https://stackoverflow.com/questions/1829605/how-to-cast-an-object-programmatically-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!