c# ValueTuple

本文探讨了ValueTuple相较于Tuple的优势,包括其作为值类型而非引用类型的特点、支持命名约定、能够创建零元素元组、提供更好的性能及灵活性等。此外,还介绍了ValueTuple的创建方式和成员访问方法。

为什么我们需要 ValueTuple?

  • Tuple 是引用类型,但 ValueTuple 是值类型。
  • Tuple 不提供命名约定,但 ValueTuple 提供了强大的命名约定。
  • 在 Tuples 中,您不能创建零分量的元组,但在 ValueTuple 中,您可以创建零元素的元组。
  • ValueTuple 的性能优于 Tuple。 因为 ValueTuple 提供了一种轻量级的机制,用于从现有方法返回多个值。 并且 ValueTuple 的语法比 Tuples 更优化。
  • ValueTuple 通过使用解构和 _ 关键字为访问值元组的元素提供了更大的灵活性。 但是 Tuple 不能提供解构的概念和 _ 关键字。
  • 在 ValueTuple 中,item1 和 item2 等成员是字段。 但在元组中,它们是属性。
  • 在 ValueTuple 中,字段是可变的。 但是在元组中,字段是只读的。

Creating a ValueTuple

  • Using Constructor

    // Constructor for creating one element
    ValueTuple(T1)
    // Constructor for creating two elements
    ValueTuple<T1, T2>(T1, T2)
    // Constructor for creating eight elements
    ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>(T1, T2, T3, T4, T5, T6, T7, TRest) /


Sample

using System;
 
class GFG {
 
    // Main method
    static public void Main()
    {
 
        // ValueTuple with one element
        ValueTuple<int> ValTpl1 = new ValueTuple<int>(345678);
 
        // ValueTuple with three elements
        ValueTuple<string, string, int> ValTpl2 = new ValueTuple<string,
                                        string, int>("C#", "Java", 586);
 
        // ValueTuple with eight elements
        ValueTuple<int, int, int, int, int, int, int, ValueTuple<int> > ValTpl3 = new ValueTuple<int,
                                  int, int, int, int, int, int, ValueTuple<int> >(45, 67, 65, 34, 34,
                                                                    34, 23, new ValueTuple<int>(90));
    }
}

  • Using Create Method

// Method for creating an empty value tuple
Create();
// Method for creating 1-ValueTuple
Create(T1)
// Method for creating 8-ValueTuple
Create<T1, T2, T3, T4, T5, T6, T7, TRest>(T1, T2, T3, T4, T5, T6, T7, T8)


Sample

using System;
 
public class GFG {
 
    // Main method
    static public void Main()
    {
 
        // Creating 0-ValueTuple
        // Using Create() Method
        var Valtpl1 = ValueTuple.Create();
 
        // Creating 3-ValueTuple
        // Using Create(T1, T2, T3) Method
        var Valtpl2 = ValueTuple.Create(12, 30, 40, 50);
 
        // Creating 8-ValueTuple
        // Using Create(T1, T2, T3, T4, T5, T6, T7, T8) Method
        var Valtpl3 = ValueTuple.Create(34, "GeeksforGeeks",
                      'g', 'f', 'g', 56.78, 4323, "geeks");
    }
}
  • Using parenthesis()

named member

using System;
 
public class GFG {
    static public void Main()
    {
        (int age, string Aname, string Lang) author = (23, "Sonia", "C#");
    }
}
using System;
 
public class GFG {
 
    static public void Main()
    {
        var author = (age : 23, Aname
                      : "Sonia", Lang
                      : "C#");
    }
}

UnNamed Member

using System;
 
public class GFG {
    static public void Main()
    {
        var author = (20, "Siya", "Ruby");
    }
}
using System;
 
public class GFG {
    static public void Main()
    {
        ValueTuple<int, string, string> author = (20, "Siya", "Ruby");
    }
}

Accessing ValueTuple members

  • Accessing unnamed members
using System;
 
public class GFG {
 
    // Main Method
    static public void Main()
    {
 
        // ValueTuple with three elements
        var author = (20, "Siya", "Ruby");
 
        // Accessing the ValueTuple
        // Using default Item property
        Console.WriteLine("Age:" + author.Item1);
        Console.WriteLine("Name:" + author.Item2);
        Console.WriteLine("Language:" + author.Item3);
    }
}
  • Accessing Named members:
using System;
 
public class GFG {
 
    // Main Method
    static public void Main()
    {
 
        // ValueTuple with three elements
        var library = (Book_id : 2340, Author_name
                       : "Arundhati Roy", Book_name
                       : "The God of Small Things");
 
        // Accessing the ValueTuple
        // according to their names
        Console.WriteLine("Book Id: {0}", library.Book_id);
        Console.WriteLine("Author Name: {0}", library.Author_name);
        Console.WriteLine("Book Name: {0}", library.Book_name);
    }
}

Returning ValueTuple

using System;
 
public class GFG {
 
    // This method returns the tourist details
    static(int, string, string) TouristDetails()
    {
        return (384645, "Sophite", "USA");
    }
 
    // Main method
    static public void Main()
    {
 
        // Store the data provided by the TouristDetails method
        var(Tourist_Id, Tourist_Name, Country) = TouristDetails();
 
        // Display data
        Console.WriteLine("Tourist Details: ");
        Console.WriteLine($ "Tourist Id: {Tourist_Id}");
        Console.WriteLine($ "Tourist Name: {Tourist_Name}");
        Console.WriteLine($ "Country: {Country}");
    }
}
### C# ValueTuple 的使用方法和示例 #### 基本概念 `ValueTuple` 是一种轻量级的数据结构,在 C# 7.0 中引入。它是值类型而非引用类型,因此相较于传统的 `Tuple` 更加高效[^4]。 #### 定义与初始化 可以通过多种方式定义和初始化 `ValueTuple`: 1. **通过构造函数显式创建** 下面展示了如何利用构造函数来实例化一个 `ValueTuple` 对象: ```csharp ValueTuple<int, string, string> valueTuple = new ValueTuple<int, string, string>(1, "Joydip", "Kanjilal"); Console.WriteLine($"{valueTuple.Item1}, {valueTuple.Item2}, {valueTuple.Item3}"); ``` 这种方式适合于需要明确指定类型的场景[^1]。 2. **隐式类型推断** 如果不想手动指定类型,可以借助编译器自动推导类型的能力: ```csharp var person = (name: "John", age: 25, city: "New York"); Console.WriteLine($"Name: {person.name}, Age: {person.age}, City: {person.city}"); ``` 此外,还可以省略命名参数并仅依赖默认项名(如 `Item1`, `Item2` 等): ```csharp var personSimple = ("Jane", 30, "Los Angeles"); Console.WriteLine($"Name: {personSimple.Item1}, Age: {personSimple.Item2}, City: {personSimple.Item3}"); ``` 隐式类型推断简化了代码编写过程,并提高了可读性[^2]。 3. **解构赋值** 解构允许将 `ValueTuple` 的各个部分分配给单独的变量: ```csharp (string name, int age, string city) = person; Console.WriteLine($"Decomposed Name: {name}, Decomposed Age: {age}, Decomposed City: {city}"); ``` 上述操作使得访问元组中的成员更加直观。 #### 性能优势 由于 `ValueTuple` 属于值类型,它的内存占用较小且不会引发垃圾回收压力。相比之下,传统 `Tuple` 则属于引用类型,可能带来额外开销[^3]。 --- ### 示例程序 以下是一段完整的演示代码,综合运用了上述知识点: ```csharp using System; class Program { static void Main() { // 显式创建 ValueTuple ValueTuple<int, string, bool> explicitTuple = new ValueTuple<int, string, bool>(1, "Hello", true); Console.WriteLine($"Explicit Tuple: {explicitTuple.Item1}, {explicitTuple.Item2}, {explicitTuple.Item3}"); // 隐式类型推断 var implicitPerson = (name: "Alice", age: 30, city: "Chicago"); Console.WriteLine($"Implicit Person: {implicitPerson.name}, {implicitPerson.age}, {implicitPerson.city}"); // 解构赋值 (string deconstructedName, int deconstructedAge, _) = implicitPerson; Console.WriteLine($"Deconstructed Values: {deconstructedName}, {deconstructedAge}"); } } ``` 运行此代码会依次打印出三个不同形式的结果,验证了各种用法的有效性。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值