c# tuple 和 switch 搭配使用
Posted cyang812
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c# tuple 和 switch 搭配使用相关的知识,希望对你有一定的参考价值。
搭配使用 tuple 和 switch
(string Str, char Separator) tuple = myEnum switch
MyEnum.RED => (text, '-'),
MyEnum.YELLOW => (text, '.'),
MyEnum.GREEN => (text, '/'),
_ => (text, 'u'),
;
测试代码
namespace Any
public class TupleSwitch
enum MyEnum
RED,
YELLOW,
GREEN
class Program
static void Main(string[] args)
MyEnum e1 = MyEnum.RED;
String e1Str1 = "Red-01";
String e1Str2 = "Red-02";
MyEnum e2 = MyEnum.YELLOW;
String e2Str1 = "Yellow.03";
String e2Str2 = "Yellow.04";
MyEnum e3 = MyEnum.GREEN;
String e3Str1 = "Green/05";
String e3Str2 = "Green/06";
int idx = 0;
if (ParseIndexFromString(e1, e1Str1, out idx))
Console.WriteLine($"idx = idx");
if (ParseIndexFromString(e1, e1Str2, out idx))
Console.WriteLine($"idx = idx");
if (ParseIndexFromString(e2, e2Str1, out idx))
Console.WriteLine($"idx = idx");
if (ParseIndexFromString(e2, e2Str2, out idx))
Console.WriteLine($"idx = idx");
if (ParseIndexFromString(e3, e3Str1, out idx))
Console.WriteLine($"idx = idx");
if (ParseIndexFromString(e3, e3Str2, out idx))
Console.WriteLine($"idx = idx");
public static bool ParseIndexFromString(MyEnum myEnum, string text, out int index)
(string Str, char Separator) tuple = myEnum switch
MyEnum.RED => (text, '-'),
MyEnum.YELLOW => (text, '.'),
MyEnum.GREEN => (text, '/'),
_ => (text, 'u'),
;
int pos = tuple.Str.IndexOf(tuple.Separator);
string subStr = tuple.Str.Substring(pos + 1).Trim();
if (int.TryParse(subStr, out index))
return true;
else
return false;
以上是关于c# tuple 和 switch 搭配使用的主要内容,如果未能解决你的问题,请参考以下文章