zoukankan      html  css  js  c++  java
  • Tuple和ValueTuple

    Tuple

    Tuple,翻译过来是元组的意思,元组听到这个词,一般会想到两个特性,一个是不可扩展,一个是顺序已定。

    这种的确灵活性不高。

    1.如何创建元组

    Tuple object=new Tuple<string,string,srting>("","","");
    Tuple object=Tuple.create<int,int,int>(1,1,1)
    

    这里需要一 一对应。

    有几个特性:

    1.只能创建7个元素,但是可以写8个,最后一个是Tuple,获取第8个元素的方式是:

    testTuple.Rest.Item1 //testTuple 余下部分

    2.tuple 只能按顺序来获取,且不能调换位置,也没有元素名称

    2.用法

    1. 当需要返回多个值得时候,可以替代out和写一个viewmodel。

    2. 比如说传入一个object,然后装箱,再拆箱。

    Tuple object=Tuple.create<int,int,int>(1,1,1);
    public void testforTuple(object object)
    {
    var objectInfo = object as Tuple<string, int, int>;
    }
    

    并不推荐使用,消耗过大,没必要,实在不行重载就好。
    ValueTuple详解

    ValueTuple是C# 7.0的新特性之一,.Net Framework 4.7以上版本可用。

    值元组也是一种数据结构,用于表示特定数量和元素序列,但是是和元组类不一样的,主要区别如下:

    值元组是结构,是值类型,不是类,而元组(Tuple)是类,引用类型;

    值元组元素是可变的,不是只读的,也就是说可以改变值元组中的元素值;

    值元组的数据成员是字段不是属性。

    优化:当构造出超过7个元素以上的值元组后,可以使用接下来的ItemX进行访问嵌套元组中的值,对于上面的例子,要访问第十个元素,既可以通过testTuple10.Rest.Item3访问,也可以通过testTuple10.Item10来访问。

    4.7内置,4.0以上NuGet能直接装System.ValueType包

    1.创建:

    和Tuple一样,不解释。

    2.用法优化

    (1)使用(string,int,uint) 可以替代创建,同时返回时用("str",1,1) 就可以对应。

    (2)返回值可以指定元素名字,方便理解记忆赋值和访问:

    (string name, int age, uint height)

    (3) 同样可用于多值传递,不推荐.

    (4) python语法来了,自己解析结构,并填充,_可忽略不需要的元素。

    static (string name, int age, uint height) GetStudentInfo1(string name)
    {
        return ("Bob", 28, 175);
    }
    
    static void RunTest1()
    {
        var (name, age, height) = GetStudentInfo1("Bob");
        Console.WriteLine($"Student Information: Name [{name}], Age [{age}], Height [{height}]");
    
        (var name1, var age1, var height1) = GetStudentInfo1("Bob");
        Console.WriteLine($"Student Information: Name [{name1}], Age [{age1}], Height [{height1}]");
    
        var (_, age2, _) = GetStudentInfo1("Bob");
        Console.WriteLine($"Student Information: Age [{age2}]");
    }
    

    序列化:

    var tempValueTuple =new ValueTuple<int,int>(1, 2);
    StringBuilder output =new StringBuilder();
    using(StringWriter writer = new StringWriter(output))
    {
    
    	XmlSerializer xs =new XmlSerializer(typeof(ValueTuple<int ,int>));
    	xs.Serialize(writer, tempValueTuple);
    }
    Console.WriteLine(output.ToString());
    
  • 相关阅读:
    HashCode和equal方法的区别和联系 [转]
    Linux makefile 教程 [转]
    gcc: multiple definition of [转]
    conda虚拟环默认路径
    terrasolid修改背景颜色
    台式机无法开机可能的原因
    TensorFlow2.1中计算平方函数的tf.square()的用法
    Terrasolid 安装教程
    如何解决Pytorch的GPU driver is too old的问题?
    使用 TensorBoard 可视化进行监督
  • 原文地址:https://www.cnblogs.com/aoximin/p/13207055.html
Copyright © 2011-2022 走看看