【问题标题】:C# syntax sugar in three conditions三种条件下的 C# 语法糖
【发布时间】:2017-07-29 21:49:42
【问题描述】:

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

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

->很简单。

但是旁边有"BUY"和"SELL"以外的价值的可能性。 以下是多余的。 请告诉我简单的表达方式。

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

【问题讨论】:

  • switch-case?.
  • 有没有在switch-case的'name variable'中设置返回值的语法?
  • 我不确定我能理解你的意思。
  • 以下是多余的。 var side = "NEITHER"; var name=""; switch(side) { case "BUY": name = "LONG";break; case "SELL": name = "SHORT"; break; default:throw new Exception(); }
  • 我认为您误用了“冗余”一词。你的意思是“臃肿”吗?

标签: c# syntax operators


【解决方案1】:

这里有一些更短的抛出异常的方法(都区分大小写):

string name1 = side == "BUY" ? "LONG" : side == "SELL" ? "SHORT" : throw new Exception();

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.'

【讨论】:

    【解决方案2】:

    如果你不介意嵌套三元:

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

    Working Fiddle here.

    如果您必须在“NEITHER”情况下抛出异常,但更喜欢 if - else if - else 构造之外的其他东西,那么切换方法可以是:

    使用系统;

    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.

    【讨论】:

    • 这应该带有“不要在家里那样做”:-)
    • @kyonoii 我认为你的 if-else if-else 方法是最好的。三元的每一项必须产生相同类型的值。
    猜你喜欢
    • 2011-08-02
    • 2011-09-01
    • 2017-12-21
    • 1970-01-01
    • 2014-04-10
    • 2010-10-19
    • 1970-01-01
    • 1970-01-01
    • 2015-11-16
    相关资源
    最近更新 更多