问题
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