gpt4 book ai didi

c# - C# 中的内联 switch/case 语句

转载 作者:太空狗 更新时间:2023-10-29 23:53:52 26 4
gpt4 key购买 nike

我很奇怪地发现我可以编写多少行代码。有没有办法将其压缩为内联案例语句?

    switch (FIZZBUZZ)
{
case "Fizz":
{
//Do one process
break;
}
case "Buzz":
{
//Do one process
break;
}
case "FizzBuzz":
{
//Do one process
break;
}
}

看起来像这样:

    switch (FIZZBUZZ)
{
case "Fizz": //Do one process
case "Buzz": //Do one process
case "FizzBuzz": //Do one process
}

最佳答案

在 C# 8 中引入。

您现在可以像这样进行切换操作:

FIZZBUZZ switch
{
"fizz" => /*do something*/,
"fuzz" => /*do something*/,
"FizzBuzz" => /*do something*/,
_ => throw new Exception("Oh ooh")
};

赋值可以这样完成:

string FIZZBUZZ = "fizz";
string result = FIZZBUZZ switch
{
"fizz" => "this is fizz",
"fuzz" => "this is fuzz",
"FizzBuzz" => "this is FizzBuzz",
_ => throw new Exception("Oh ooh")
};
Console.WriteLine($"{ result }"); // this is fizz

函数调用:

public string Fizzer()     => "this is fizz";
public string Fuzzer() => "this is fuzz";
public string FizzBuzzer() => "this is FizzBuzz";
...
string FIZZBUZZ = "fizz";

string result = FIZZBUZZ switch
{
"fizz" => Fizzer(),
"fuzz" => Fuzzer(),
"FizzBuzz" => FizzBuzzer(),
_ => throw new Exception("Oh ooh")
};
Console.WriteLine($"{ result }"); // this is fizz

每个案例的多个内联操作(我认为委托(delegate)是必须的):

string FIZZBUZZ = "fizz";
string result = String.Empty;

_= (FIZZBUZZ switch
{
"fizz" => () =>
{
Console.WriteLine("fizz");
result = "fizz";
},
"fuzz" => () =>
{
Console.WriteLine("fuzz");
result = "fuzz";
},
_ => new Action(() => { })
});

您可以在此处阅读有关新开关盒的更多信息:What's new in C# 8.0

关于c# - C# 中的内联 switch/case 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3415936/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com