假設我有這樣一個自定義的控制:如何在運行時以編程方式投射對象?
MyControl : Control
,如果我有這樣的代碼:
List<Control> list = new ...
list.Add (myControl);
RolloutAnimation anim = list[0];
我知道我可以在編譯的時候做,但我想在運行時訪問MyControl做具體的功能。
假設我有這樣一個自定義的控制:如何在運行時以編程方式投射對象?
MyControl : Control
,如果我有這樣的代碼:
List<Control> list = new ...
list.Add (myControl);
RolloutAnimation anim = list[0];
我知道我可以在編譯的時候做,但我想在運行時訪問MyControl做具體的功能。
爲什麼你想在運行時做到這一點?如果您有更多類型的列表控件,有一些特定的功能,但不同類型的,或許他們應該實現一個共同的接口:
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();
謝謝,但在這種情況下,我應該使用什麼類型的名單?控制或界面? – 2009-12-01 23:29:11
不錯的建議 – 2009-12-01 23:34:50
這個列表是'List
((MyControl)list[0]).SomeFunction()
謝謝,但我想在運行時,如列表[0] .Cast(列表[0] .GetType())等, – 2009-12-01 23:15:36
我想你可能會對「運行時間」的含義感到困惑。這意味着「程序正在執行」。 – 2009-12-01 23:22:33
我的意思是這樣的: http://stackoverflow.com/questions/345506/whats-the-runtime-equivalent-of-c-bracketed-type-cast – 2009-12-01 23:25:15
(MyControl)list[0]
將返回類型MyControl的對象,或者拋出錯誤,如果列表[0]不是MyControl。
list[0] as MyControl
將返回一個類型MyControl的對象或null如果列表[0]類型MyControl不
您還可以查看列表的類型類型[0]測試list[0] is MyControl
完全偏離主題,但我總是討厭作爲Object方法。意思是我後來得到一個空引用異常,而不是發生實際錯誤的地方(轉換的位置)。它導致了相當多的有趣的bug搜尋...... – Rontologist 2009-12-01 23:18:41
非常好的一點。很高興記得「as」。 – 2009-12-01 23:25:13
@Rontologist如果使用得當,請勿使用。但事實上很多人都認爲它比演員表「看起來更好」,這會帶來麻煩。 – 2009-12-01 23:29:02
MyControl my_ctrl = list[0] as MyControl;
if(my_ctrl != null)
{
my_ctrl.SomeFunction();
}
// Or
if(list[0] is MyControl)
{
((MyControl)list[0]).SomeFunction();
}
爲什麼你要在運行時做呢?如果列表中有更多類型的控件,它們有一些特定的功能,但類型不同,可能它們應該實現一個通用接口。 – luvieere 2009-12-01 23:19:51
謝謝。你認爲這是更好的方法嗎? – 2009-12-01 23:22:33
我已經將它添加爲答案,我確實認爲這是一種比通過多次投射驗證多種類型更好的方法。通過一個接口,你只需要確保你的Control類實現了它,然後你只需要添加所有的接口實例,裏面的函數就可以訪問。 – luvieere 2009-12-01 23:29:50