C#语法糖在三个条件下

时间:2017-03-09 03:55:41

标签: c# syntax operators

我想知道C#中的语法糖。

var name = side=="BUY" ? "LONG" : "SHORT";

- >这非常简单。

但除了"购买"之外,还有价值的可能性。和"卖出"在一边。 以下是多余的。 请告诉我简单的表达方式。

var name;
if (side == "BUY")
    name="LONG";
else if(side="SELL")
    name="SHORT";
else
    throw Exception();

2 个答案:

答案 0 :(得分:1)

如果你不介意嵌套三元:

var name = side == "BUY"
    ? "LONG"
    : side == "SELL"
        ? "SHORT"
        : "NEITHER";

Working Fiddle here

如果你必须在“NEITHER”案例中抛出一个异常,但是除了if之外的其他东西 - 否则if - else构造,那么切换方法可能是:

使用System;

public class Program
{
    public static void Main()
    {
        var side = "Foo";   // or "BUY" or "SELL" or whatever
        var name = "NEITHER";
        switch (side)
        {
            case "BUY":
                name = "LONG";
                break;
            case "SELL":
                name = "SHORT";
                break;
            default:
                throw new Exception();
        }
        Console.WriteLine(name);
    }
}

Working Fiddle here

答案 1 :(得分:1)

以下是一些抛出异常的简短方法(所有区分大小写):

string name1 = side == "BUY" ? "LONG" : side == "SELL" ? "SHORT" : side.Remove(-1); // System.ArgumentOutOfRangeException: 'StartIndex cannot be less than zero.'

string name2 = new[] { "LONG", "SHORT" }[Array.IndexOf(new[] { "BUY", "SELL" }, side)]; // System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'

string name3 = new Dictionary<string, string> { { "BUY", "LONG" }, { "SELL", "SHORT" } }[side]; // System.Collections.Generic.KeyNotFoundException: 'The given key was not present in the dictionary.'