[英]Switch-case of EventArg types
是否可以圍繞EventArgs創建switch-case語句?
即:
void MyMethod(object sender, EventArgs e)
{
switch(e)
{
//MyEventArgs inherit from EventArgs
case e is MyEventArgs:
//Do some code...
break;
default:
break;
}
}
現在我找不到將其放置在switch-case中的方法,所以我使用的是if-else語句,當我在其中填充很多if-else時,這比switch-case的速度要慢(因為switch -case在引擎蓋下創建某種case的哈希表)。
您不能在方案中使用switch
。
switch
語句需要整數類型或字符串作為參數(下面有更多詳細信息) 。 您不能將EventArgs
作為參數傳遞給switch語句, case
語句也需要編譯時常數值。
如果您查看C#5.0規范 :
switch語句的控制類型由switch表達式建立。
- 如果switch表達式的類型是sbyte,byte,short,ushort,int,uint,long,ulong,bool,char,string或enum類型,或者它是與這些類型之一相對應的可空類型,然后
是switch語句的控制類型。- 否則,從switch表達式的類型到以下之一,必須存在一個用戶定義的隱式轉換(第6.4節)
可能的管理類型:sbyte,byte,short,ushort,int,uint,
long,ulong,char,string或對應於一個的可空類型
這些類型。- 否則,如果不存在此類隱式轉換,或者存在多個此類隱式轉換, 則會發生編譯時錯誤。
代碼中的另一個問題是case語句:
每個案例標簽都指定一個常量值。
您的case語句指定了在編譯時無法確定的值。
這使您可以選擇使用if-else
塊。 除非您要處理數百種EventArgs
,否則您幾乎不可能看到任何明顯的性能提升。
在開關櫃中,每種情況都必須進行靜態評估。 這意味着在每種情況下都需要一個常量。 這篇文章對C#switch語句的限制也許也有用-為什么?
您可以使用Dictionary<Type, Action<EventArgs>>
嘗試:
private static Dictionary<Type, Action<EventArgs>> _EventDispatcher;
static Program()
{
_EventDispatcher = new Dictionary<Type, Action<EventArgs>>();
_EventDispatcher.Add(typeof(EventArgs), OnEventArgs);
_EventDispatcher.Add(typeof(MyEventArgs), OnMyEventArgs);
}
private static void MyMethod(object sender, EventArgs e)
{
Action<EventArgs> eventMethod;
if (!_EventDispatcher.TryGetValue(e.GetType(), out eventMethod))
eventMethod = OnUnknownEventArgs;
eventMethod(e);
}
private static void OnEventArgs(EventArgs e)
{
Console.WriteLine("Simple event args: " + e);
}
private static void OnMyEventArgs(EventArgs e)
{
var myEventArgs = (MyEventArgs)e;
Console.WriteLine("My event args: " + myEventArgs);
}
private static void OnUnknownEventArgs(EventArgs e)
{
Console.WriteLine(String.Format("Unknown event args ({0}): {1}", e.GetType(), e);
}
private static void Main(string[] args)
{
MyMethod(null, new EventArgs());
MyMethod(null, new MyEventArgs());
MyMethod(null, new AnotherEventArgs());
Console.ReadKey();
}
您是否考慮過使用方法重載? 通常來說,我會盡量避免使用切換例外情況,除非有視圖異常,因為它們經常是繼承,重載等可以更好地解決問題的氣味。
BR
只為完整性,這會工作,但你不應該這樣做,其原因應該是很明顯的:
void MyMethod(object sender, EventArgs e)
{
switch(e.GetType().FullName)
{
case "MyNamespace.MyEventArgs":
//seriously, don't do this.
break;
case "System.EventArgs":
//this is the worst idea ever.
break;
default:
break;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.