搭配使用 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;
}
}
}
}
}