3

次のように、各ケース ブロックが中括弧で囲まれている switch ステートメントの例を見てきました。

switch (itemType)
{
    case ItemType.TV:
    {
        String message = Messages.GetMessage(itemType);
        Console.WriteLine(message);
        break;
    }
    case ItemType.Computer:
    {
        XPMessage message = XPMessage.Next();
        if(message.Data == "XC12")
            message.IsValid = true;

        break;
    }
    case ItemType.WashingMachine:
    {
        String message = "Washing machines are so cool.";
        Messages.SendMessage(message, itemType);
        break;
    }
    default:
    {
        break;
    }
}

私が知っている唯一の利点は、宣言の範囲を制限することです (例を参照)。

ただし、そのような種類のコード ブロックでコードの一部を分離するための他の良い用途があるかどうかを知りたいです(ここでは必ずしも switch ステートメント内ではないことを意味します)。

いつ、どのように使用しますか。使用しない場合は、なぜ使用しないのですか?

また、そのようなコード ブロックを使用することの欠点はありますか?

4

2 に答える 2

4

As you said declaration scope is one of them and also readability. Some people think it's much easier to see the braces rather than having to keep going until they see a break statement. It seems to be a personal preference. In this case it's done for scoping purposes because not all the statements use the same data type.

于 2011-07-07T05:37:15.383 に答える
2

It's just a stylistic thing that some people prefer for readability/white space, when not done for scope purposes.

There are no additional benefits that I am aware of.

于 2011-07-07T05:42:36.457 に答える