Csahrp_Tuple元组

 Tuple是在C#7.1之后添加的新的数据结构类型
能够用来表示一种组合的数据类型(有点像设计模式里的组合模式)
 第一次认识元组这个词是在Python中,现在在C#中也能方便的使用这一种数据类型了
就好像java也支持var关键字一样,各个编程语言都在逐渐靠拢,吸收彼此的优点
我们写代码也应该灵活运用,发挥出代码的力量

            region Tuple和ValueTuple的使用   

//创建一个Tuple(可以发现,Tuple可以容纳1-n个数据           
            Tuple<int, string, bool> tuple = new Tuple<int, string, bool>(10, "hello", true);
            //获取Tuple的组件(每一项会被封装为Item的一项属性(只有get方法),故只能在初始化时进行赋值
            int a = tuple.Item1;
            string b = tuple.Item2;
            bool c = tuple.Item3;
            //可以创建Tuple的数组(且可以嵌套
            Tuple<int, string>[] tuples = new Tuple<int, string>[] { new Tuple<int, string>(100, "s"), new Tuple<int, string>(1000, "sss") };
           
 //ValueTuple 是Tuple的加强版,具有空构造,且每一项Item都可以赋值
            ValueTuple<int, string, bool> vaa = new ValueTuple<int, string, bool>();
            vaa.Item1 = 10;
            vaa.Item2 = "Hello World";
            vaa.Item3 = true;
            
            //Tuple 和ValueTuple在返回多个值时也有不小的用途,具体请看下面的例子

 方法返回多个值
         
 //ValueTuple 是Tuple的加强版,具有空构造,且每一项Item都可以赋值
            ValueTuple<int, string, bool> vaa = new ValueTuple<int, string, bool>();
            vaa.Item1 = 10;
            vaa.Item2 = "Hello World";
            vaa.Item3 = true;
            
            //Tuple 和ValueTuple在返回多个值时也有不小的用途,具体请看下面的例子



         
  //1.使用out参数进行多个值的返回
            //---------需要在外部声明好out 参数的变量,对于out参数没有一个统一的管理
            int bb = 0, cc = 0;
            int aa = GetY(1, out bb,out cc);
            Console.WriteLine("aa={0} bb={1} cc={2}",aa,bb,cc);


            //2.使用Tuple进行多个值返回
            //-------------不存在数组越界,也不必强制转换,无需外部变量,但是Item的名称不能自定义
            var va = GetZ();
            int data_aa = va.Item1;
            string data_bb = va.Item2;
            bool data_cc = va.Item3;
            Console.WriteLine("data_aa={0} data_bb={1} data_cc={2}", data_aa, data_bb, data_cc);


            //3.使用ValueTuple进行多个值返回
            //-------无需外部变量,不存在数组越界,能以自定义的方式访问数据而不是Item,不必强制转换
            //-----封装到一个对象上,是最好的选择
            var vall = Get(1, "Ai");
            Console.WriteLine("id={0}\tname={1}\tpass={2}",vall.id,vall.name,vall.isPass);
           
 返回多个值_方法声明
       
 //数组返回多个值
        static object[] GetX()
        {
            return new object[] { 1, "Hi", true };
        }
        //out返回多个值
        static int GetY(int cc,out int a,out int b)
        {
            a = 10;
            b = 20;
            return cc;
        }
        //Tuple返回多个值
        static Tuple<int,string,bool> GetZ()
        {
            return new Tuple<int, string, bool>(10, "hi_tuple", false);
        }


        //valueTuple返回多个值
        static (int id,string name,bool isPass) Get(int a, string b)
        {
           
            return (a,b,true);
        }

猜你喜欢

转载自blog.csdn.net/qq_37446649/article/details/80210824