您可以創建一個Dictionary<Type, Action<object>>
和存儲從a
的GetType
method的類型(返回值與執行要取其代碼代表一起運行一個給定的類型。
例如,看看這個:
private readonly Dictionary<Type, Action<object>> typeActions = new Dictionary<Type, Action<object>>()
{
{ typeof(int), (a) => { Console.WriteLine(a.ToString() + " is an integer!"); } },
{ typeof(float), (a) => { Console.WriteLine(a.ToString() + " is a single-precision floating-point number!"); } }
};
本詞典然後可以在其他地方在你的代碼中使用:
Action<object> action;
if (typeActions.TryGetValue(a.GetType(), out action)) {
action(a);
}
注意,你仍然要內施放a
爲適當的類型你的行爲。
編輯:由於Chris正確指出,如果a
屬於註冊類型的子類,這將不會識別a.GetType()
。如果需要包括,你將不得不走的類型層次結構:如果你需要覆蓋泛型類型和/或接口
Action<object> action = null;
for (Type t = a.GetType(); t = t.BaseType; t != null) {
if (typeActions.TryGetValue(t, out action)) {
break;
}
}
if (action != null) {
action(a);
}
,這是可行的,太多,但代碼將成爲穩步更加複雜。
如何查看var關鍵字,那樣變量var就是那個對象的類型。 – lloydom
switch(a.getType()。ToString()) – StampedeXV
@StampedeXV認真嗎?我的意思是,沒有冒犯,但*不寒而慄* – PoByBolek