Ban*_*nny 25 .net c# logic switch-statement switch-expression
我想使用一个switch语句,它接受几个变量,如下所示:
switch (intVal1, strVal2, boolVal3)
{
case 1, "hello", false:
break;
case 2, "world", false:
break;
case 2, "hello", false:
etc ....
}
Run Code Online (Sandbox Code Playgroud)
有没有办法在C#中做这样的事情?(出于显而易见的原因,我不想使用嵌套的switch语句).
Ste*_*edy 33
是的。从 .NET 4.7 和 C# 8 开始支持它。语法与您提到的几乎相同,但带有一些括号(请参阅 元组模式)。
switch ((intVal1, strVal2, boolVal3))
{
case (1, "hello", false):
break;
case (2, "world", false):
break;
case (2, "hello", false):
break;
}
Run Code Online (Sandbox Code Playgroud)
如果您想切换并返回一个值,则有一个切换“表达式语法”。这是一个例子;注意_默认情况下的使用:
string result = (intVal1, strVal2, boolVal3) switch
{
(1, "hello", false) => "Combination1",
(2, "world", false) => "Combination2",
(2, "hello", false) => "Combination3",
_ => "Default"
};
Run Code Online (Sandbox Code Playgroud)
这是上面链接的 MSDN 文章中的一个更具说明性的示例(石头、纸、剪刀游戏):
public static string RockPaperScissors(string first, string second)
=> (first, second) switch
{
("rock", "paper") => "rock is covered by paper. Paper wins.",
("rock", "scissors") => "rock breaks scissors. Rock wins.",
("paper", "rock") => "paper covers rock. Paper wins.",
("paper", "scissors") => "paper is cut by scissors. Scissors wins.",
("scissors", "rock") => "scissors is broken by rock. Rock wins.",
("scissors", "paper") => "scissors cuts paper. Scissors wins.",
(_, _) => "tie"
};
Run Code Online (Sandbox Code Playgroud)
Ste*_*edy 26
您可以使用以下when关键字在C#7及更高版本中执行此操作:
switch (intVal1)
{
case 1 when strVal2 == "hello" && boolVal3 == false:
break;
case 2 when strVal2 == "world" && boolVal3 == false:
break;
case 2 when strVal2 == "hello" && boolVal3 == false:
break;
}
Run Code Online (Sandbox Code Playgroud)
Aar*_*ght 12
让我们看看另一种方式.如果你有:
int,bool,string等)然后你可以使用一个查找表,它具有与switch语句类似的执行速度但效率不高(因为它需要计算哈希值).不过,它可能还不错.并且它为您提供了命名案例的机会,使这种组合爆炸稍微减少混乱和不可维护.
一个代码示例:
private static readonly Tuple<int, int, bool> NameOfCase1 =
Tuple.Create(1, 1, false);
private static readonly Tuple<int, int, bool> NameOfCase2 =
Tuple.Create(2, 1, false);
private static readonly Tuple<int, int, bool> NameOfCase3 =
Tuple.Create(2, 2, false);
private static readonly Dictionary<Tuple<int, int, bool>, string> Results =
new Dictionary<Tuple<int, int, bool>, string>
{
{ NameOfCase1, "Result 1" },
{ NameOfCase2, "Result 2" },
{ NameOfCase3, "Result 3" }
};
public string GetResultForValues(int x, int y, bool b)
{
const string defaultResult = "Unknown";
var lookupValue = Tuple.Create(x, y, b);
string result;
Results.TryGetValue(lookupValue, out result);
return defaultResult;
}
Run Code Online (Sandbox Code Playgroud)
如果您需要为每个案例实际执行一个函数或方法,那么您可以使用Action<T>或Func<T>代替结果类型(字典值).
请注意我在Tuple<T1,T2,T3>这里使用,因为它已经内置了所有哈希代码逻辑.语法在C#中有点尴尬但是如果你愿意,你可以实现自己的查找类,只需覆盖Equals和GetHashCode.
Pao*_*sco 10
在C#中没有内置功能来执行此操作,我不知道有任何库可以执行此操作.
这是一种替代方法,使用Tuple和扩展方法:
using System;
static class CompareTuple {
public static bool Compare<T1, T2, T3>(this Tuple<T1, T2, T3> value, T1 v1, T2 v2, T3 v3) {
return value.Item1.Equals(v1) && value.Item2.Equals(v2) && value.Item3.Equals(v3);
}
}
class Program {
static void Main(string[] args) {
var t = new Tuple<int, int, bool>(1, 2, false);
if (t.Compare(1, 1, false)) {
// 1st case
} else if (t.Compare(1, 2, false)) {
// 2nd case
} else {
// default
}
}
}
Run Code Online (Sandbox Code Playgroud)
这基本上只是提供一个方便的语法来检查多个值 - 并使用多个ifs而不是开关.
我彻头彻尾的疯狂对此:
class Program
{
static void Main(string[] args)
{
var i = 1;
var j = 34;
var k = true;
Match(i, j, k).
With(1, 2, false).Do(() => Console.WriteLine("1, 2, 3")).
With(1, 34, false).Do(() => Console.WriteLine("1, 34, false")).
With(x => i > 0, x => x < 100, x => x == true).Do(() => Console.WriteLine("1, 34, true"));
}
static Matcher<T1, T2, T3> Match<T1, T2, T3>(T1 t1, T2 t2, T3 t3)
{
return new Matcher<T1, T2, T3>(t1, t2, t3);
}
}
public class Matcher<T1, T2, T3>
{
private readonly object[] values;
public object[] Values
{
get { return values; }
}
public Matcher(T1 t1, T2 t2, T3 t3)
{
values = new object[] { t1, t2, t3 };
}
public Match<T1, T2, T3> With(T1 t1, T2 t2, T3 t3)
{
return new Match<T1, T2, T3>(this, new object[] { t1, t2, t3 });
}
public Match<T1, T2, T3> With(Func<T1, bool> t1, Func<T2, bool> t2, Func<T3, bool> t3)
{
return new Match<T1, T2, T3>(this, t1, t2, t3);
}
}
public class Match<T1, T2, T3>
{
private readonly Matcher<T1, T2, T3> matcher;
private readonly object[] matchedValues;
private readonly Func<object[], bool> matcherF;
public Match(Matcher<T1, T2, T3> matcher, object[] matchedValues)
{
this.matcher = matcher;
this.matchedValues = matchedValues;
}
public Match(Matcher<T1, T2, T3> matcher, Func<T1, bool> t1, Func<T2, bool> t2, Func<T3, bool> t3)
{
this.matcher = matcher;
matcherF = objects => t1((T1)objects[0]) && t2((T2)objects[1]) && t3((T3)objects[2]);
}
public Matcher<T1, T2, T3> Do(Action a)
{
if(matcherF != null && matcherF(matcher.Values) || matcher.Values.SequenceEqual(matchedValues))
a();
return matcher;
}
}
Run Code Online (Sandbox Code Playgroud)
您可以转换为字符串:
switch (intVal1.ToString() + strVal2 + boolVal3.ToString())
{
case "1helloFalse":
break;
case "2worldFalse":
break;
case "2helloFalse":
etc ....
}
Run Code Online (Sandbox Code Playgroud)
不过,我认为要解决的问题是是否有更好的定义逻辑的方法。例如,假设您想弄清楚谁认识超人。我们可以这样检查:
switch (first + last)
{
case "ClarkKent":
case "LoisLane":
// YES
break;
default;
// Sadly, no
break;
}
Run Code Online (Sandbox Code Playgroud)
但是当你得到另一个叫克拉克肯特的人时会发生什么?你真的不能有一些其他的值来确定这个逻辑,即 bool KnowsSuperman 吗?
这个想法是,一个 switch 语句用于根据一组选择来确定逻辑。如果您试图关闭多个值,那么逻辑可能会变得非常难以维护。
另一个例子是,如果你需要将人们分成几个组并根据他们所在的组执行一些逻辑。你可以编写代码说,如果你是 Bob、Jeff、Jim 或 Sally,你是在 A 组中,但是如果您需要将其他人添加到 A 组中怎么办?您必须更改代码。相反,您可以创建一个名为 Group 的额外属性,它可以是一个枚举或字符串,您可以使用它来指定某人所在的组。
| 归档时间: |
|
| 查看次数: |
33098 次 |
| 最近记录: |