2012-09-14 27 views
8

假設我有一堆靜態字段的,我想在交換機使用它們:switch語句與靜態字段

public static string PID_1 = "12"; 
public static string PID_2 = "13"; 
public static string PID_3 = "14"; 

switch(pid) 
{ 
    case PID_1: 
     //Do something 1 
     break; 
    case PID_2: 
     //Do something 2 
     break; 
    case PID_3: 
     //Do something 3 
     break; 
    default: 
     //Do something default 
     break; 
} 

由於C#不允許內部開關非const語句。我想了解這種設計的意圖是什麼。我應該如何在c#中做類似上面的事情?

+2

將PID_1 PID_2等的值的變化? –

+0

Mr.Mindor。不,但我希望它們也是靜態的。 – Ashutosh

+1

@Ashutosh所有'const'值都是靜態的。他們不與班級的實例掛鉤。你不使用'static',因爲它是多餘的,不是因爲它不可能。 – Servy

回答

16

它看起來像那些字符串值應該只是常數。

public const string PID_1 = "12"; 
public const string PID_2 = "13"; 
public const string PID_3 = "14"; 

如果這不是一個選項(它們在運行時實際改變),那麼你就可以重構該解決方案爲一系列的if/else if語句的。

至於爲什麼案例陳述需要保持不變;通過讓它們保持不變,它可以使語句更加優化。它實際上比一系列的if/else if語句更有效率(儘管如此,如果您沒有花費很長時間的條件檢查批次)。它將生成與case語句值作爲關鍵字的哈希表的等效項。如果這些值可能發生變化,則不能使用該方法。

+0

好的。所以爲什麼我們不能使用只讀字段?使用const不是一個選項。擁有一個公共靜態對於常量標識符更有意義..我不能在任何我想要的地方使用它們,並且我只有一個它的實例... – Ashutosh

+2

@Ashutosh您不能使用只讀字段,因爲直到運行; switch語句會導致在編譯時生成一個表,這就是case語句都需要編譯時間常量的原因。 '「擁有公共靜態更有意義」如果這些值實際上是恆定的,我不會同意。如果值實際上是常量,那麼使用'const'值會更有意義。請注意,所有的'const'值都是靜態的。它們根本不依賴於對象的實例。 – Servy

2

在編譯時應該保持不變。

嘗試使用const代替:

public const string PID_1 = "12"; 
public const string PID_2 = "13"; 
public const string PID_3 = "14"; 
+0

@亨克:謝謝!多麼愚蠢的錯字:) – abatishchev

3

... C#不允許內部開關非const語句...

如果你不能使用:

public const string PID_1 = "12"; 
public const string PID_2 = "13"; 
public const string PID_3 = "14"; 

您可以使用詞典:)

.... 
public static string PID_1 = "12"; 
public static string PID_2 = "13"; 
public static string PID_3 = "14"; 



// Define other methods and classes here 

void Main() 
{ 
    var dict = new Dictionary<string, Action> 
    { 
    {PID_1,()=>Console.WriteLine("one")}, 
    {PID_2,()=>Console.WriteLine("two")}, 
    {PID_3,()=>Console.WriteLine("three")}, 
    }; 
    var pid = PID_1; 
    dict[pid](); 
} 
+0

我只是寫這個了。 –

1

我假設你沒有聲明這些變量的原因是const。這就是說:

switch聲明只是一堆if/else if陳述的簡寫。所以,如果你能保證PID_1PID_2,並PID_3永遠是平等的,上面是相同的:

if (pid == PID_1) { 
    // Do something 1 
} 
else if (pid == PID_2) { 
    // Do something 2 
} 
else if (pid == PID_3) { 
    // Do something 3 
} 
else { 
    // Do something default 
} 
+0

切換字符串也可以作爲字典實現(https://stackoverflow.com/a/3366497/616827)。 – Jeff

1

的規範方式來處理這一點 - 如果你的靜態字段不實際常量 - 將使用一個Dictionary<Something, Action>

static Dictionary<string, Action> switchReplacement = 
    new Dictionary<string, Action>() { 
     { PID_1, action1 }, 
     { PID_2, action2 }, 
     { PID_3, action3 }}; 

// ... Where action1, action2, and action3 are static methods with no arguments 

// Later, instead of switch, you simply call 
switchReplacement[pid].Invoke();