zoukankan      html  css  js  c++  java
  • c#元组举例

    数组合并了相同类型的对象,而元组合并了不同类型的对象。元组起源于函数编程语言(如F#) ,在
    这些语言中频繁使用元组。在N盯4中,元组可通过.NET Fmmework用于所有的NET语言。
    .NET 4定义了8个泛型Tuple类和一个静态Tuple类,它们用作元组的工厂。这里的不同泛型Tuple
    类支持不同数量的元素。例如,Tuple<T1>包含-个元素,Tuple<T1,T2>包含两个元素,以此类推。

    1.第一个例子

            private Tuple<int, int> Divide(int dividend, int divisor)
            {
                int result = dividend / divisor;
                int reminder = dividend % divisor;
                return Tuple.Create<int, int>(result, reminder);           //返回两个相同类型元素的元组
            }

           --------测试-------------

            private void button1_Click(object sender, EventArgs e)
            {
                Tuple<int, int> result = Divide(13, 2);
                Console.WriteLine("result of divison:{0}," +
                    "reminder:{1}", result.Item1, result.Item2);                //用属性item1,item2访问元组的项
            }

           -------结果-------------

           result of divison:6,reminder:1

    2.第二个例子

            private Tuple<int, string> MyTest2(int dividend, string Name)
            {
                int result = dividend / 2;
                string name = "Hello," + Name;
                return Tuple.Create<int, string>(result, name);      //返回两个不同类型元素的元组
            }

            --------测试-------------

            private void button2_Click(object sender, EventArgs e)
            {
                Tuple<int, string> result = MyTest2(13, "limin");
                Console.WriteLine("result of divison:{0}," +
                    "Name:{1}", result.Item1, result.Item2);                //用属性item1,item2访问元组的项
            }

            -------结果-------------

            result of divison:6,Name:Hello,limin

    3.第三个例子

    如果元组包含的项超过8个,就可以使用带8个参数的Tuple类定义。最后一个模板参数是TRest ,
    表示必须给它传递一个元组。这样,就可以创建带任意个参数的元组了。
    下面说明这个功能:
    public class Tuple<T1,T2,T3,T4,T5,T6,T7,TRest>
    其中,最后一个模板参数是一个元组类型,所以可以创建带任意多项的元组:
    var tuple = Tuple.Create<string,string,string, int,int,int,double,
    Tuple<int,int>>(
    "stephanie","Alina","Nagel", 2009,6,2,1.37,
    Tuple.Create<int,int> (52,3490));

  • 相关阅读:
    前端与算法 leetcode 28.实现 strStr()
    前端与算法 leetcode 27.移除元素
    npm钉钉脚手架,支持考勤信息获取
    VSCode 使用Settings Sync同步配置(最新版教程,非常简单)
    VSCode 远程开发(带免密)
    vscode保存代码,自动按照eslint规范格式化代码设置
    matplotlib 3D数据-【老鱼学matplotlib】
    matplotlib等高线图-【老鱼学matplotlib】
    matplotlib柱状图-【老鱼学matplotlib】
    matplotlib散点数据-【老鱼学matplotlib】
  • 原文地址:https://www.cnblogs.com/KSalomo/p/6531094.html
Copyright © 2011-2022 走看看