C# Tuple<T1,T2....T>元组的使用

1)

先说组元:一个数据结构,由通过逗号分割的,用于传递给一个程序或者操作系统的一系列值的组合。

NET Framework 直接支持一至七元素的元组

Tuple<T1, T2, T3, T4, T5, T6, T7>
此外,您可以通过嵌套的元组中的对象创建八个或多个元素的元组在Rest 属性中的Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> 对象。

简单的示例:
[csharp]  view plain  copy
 
  1. //一个元素的元组  
  2. Tuple<int> test = new Tuple<int>(34);  
  3.   
  4. //两个元素的元组 1<n<8  
  5. Tuple<string, int> test2 = Tuple.Create<string, int>("str", 2);  
  6. Tuple<int, int> test2_1 = new Tuple<int, int>(2,2);  
  7.   
  8. //8个元素的元组(注意,Tuple<类型...>: 基本"类型"最多7个, 第八个元素类型必须也为元组)  
  9. Tuple<int, int, int, int, int, int, int, Tuple<int>> test3 =   
  10. new Tuple<int, int, int, int, int, int, int, Tuple<int>>(1, 2, 3, 4, 5, 6, 7, new Tuple<int>(8));  
  11.   
  12. //也可以这样  
  13. Tuple<int, int, Tuple<int, int>> test_i_i_Tii = new Tuple<int, int, Tuple<int, int>>(1,1,new Tuple<int,int>(2,3));  
  14. Console.WriteLine(test.Item1);  
  15. Console.WriteLine(test2.Item1 + test2.Item2);  
  16. Console.WriteLine(test2_1.Item1 + test2_1.Item2);  
  17. Console.WriteLine(test3.Item1 + test3.Item2 + test3.Item3 + test3.Item4 + test3.Item5 + test3.Item6 + test3.Item7 + test3.Rest.Item1);  
结果:


2)多个返回值问题
一般我们都是用out关键字(相比其他语言,如golang,out关键字还是稍微有点麻烦),此时我们可以使用元组实现:
[csharp]  view plain  copy
 
  1. namespace TupleDemo  
  2. {  
  3.     class Program  
  4.     {  
  5.         static void Main(string[] args)  
  6.         {  
  7.   
  8.             //使用out拿到多个返回值  
  9.             string outparam = "";  
  10.             int returnvalue = FunOutParamDemo(out outparam);  
  11.             Console.WriteLine(returnvalue + "    " + outparam);  
  12.   
  13.             //使用元组拿到多个返回值  
  14.             Tuple<int, string> r = FunTupleParamDemo();  
  15.             Console.WriteLine(r.Item1 + "    " + r.Item2);  
  16.   
  17.             Console.Read();  
  18.         }  
  19.         /// <summary>  
  20.         /// out关键字,实现返回两个返回值  
  21.         /// </summary>  
  22.         /// <param name="o"></param>  
  23.         /// <returns></returns>  
  24.         public static int FunOutParamDemo(out string o)  
  25.         {  
  26.             o = "returnValue";  
  27.             return 10;  
  28.         }  
  29.   
  30.         /// <summary>  
  31.         /// 使用元组实现【间接】返回【两个】返回值  
  32.         /// </summary>  
  33.         /// <returns></returns>  
  34.         public static Tuple<int, string> FunTupleParamDemo() {  
  35.             return new Tuple<int, string>(10, "returnValue");  
  36.         }  
  37.     }  
  38. }  
运行结果:

转载于:https://www.cnblogs.com/mschen/p/8333903.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值