16

たくさんの静的フィールドがあり、それらをスイッチで使用したいとします。

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# では、switch 内で非 const ステートメントを使用できないためです。この種の設計の意図が何であるかを理解したいです。上記のようなことをC#で行うにはどうすればよいですか?

4

7 に答える 7

32

これらの文字列値は単純に一定である必要があるようです。

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 ステートメントの値をキーとして持つハッシュ テーブルに相当するものを生成します。値が変わる可能性がある場合、そのアプローチは使用できません。

于 2012-09-14T18:25:17.953 に答える
4

... C# では、switch 内で非 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](); 
}
于 2012-09-14T18:27:56.117 に答える
3

case 引数は、コンパイル時に一定でなければなりません。

const代わりに使用してみてください:

public const string PID_1 = "12";
public const string PID_2 = "13";
public const string PID_3 = "14";
于 2012-09-14T18:25:26.460 に答える
1

これらの変数を として宣言しなかった理由があると思いますconst。それは言った:

このswitchステートメントは、一連のステートメントの省略形ですif / else if。したがって、 、、およびが決して等しくないことを保証できる場合、上記は次と同等です。PID_1PID_2PID_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
}
于 2012-09-14T18:28:23.433 に答える
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();
于 2012-09-14T18:31:31.210 に答える
1

enum を使用しないのはなぜですか?
列挙型キーワード:
http://msdn.microsoft.com/en-us/library/sbbt4032%28v=vs.80%29.aspx

あなたの場合、列挙型で簡単に処理できます:

public enum MyPidType
{
  PID_1 = 12,
  PID_2 = 14,
  PID_3 = 18     
}
于 2012-09-15T00:10:29.750 に答える