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;
                }
            }
        }

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值