总目录
C# 语法总目录
元组(tuple)是一组存储值的便捷方式。
元组的目的主要是,不使用out参数而从方法中返回多个值。(匿名类型无法做这个操作)元组能做匿名类型所有操作。
元组是值类型,并且它是可变(可读可写)的元素
static void Main(string[] args)
{
var person = ("lisi", 20);
Console.WriteLine(person.Item1);
Console.WriteLine(person.Item2);
}
//输出
lisi
20
var person1 = person;
person1.Item1 = "zhangsan";
Console.WriteLine(person1.Item1);
//输出
zhangsan
//元组的类型
(string,int) person = ("lisi",20);
//返回元组类型的方法
static (string,int) GetPerson()=>("lisi",20);
static void Main()
{
(string,int) person = GetPerson();
Console.WriteLine(person.Item1); //输出 lisi
}
元组可以搭配泛型使用
Dictionary<(string,int),int>
IEnumerable<int ID,string Name>
var tuple = (Name:"lisi",Age:20);
Console.WriteLine(tuple.Name); //lisi
//或者
static (string Name,int Age) GetPerson()=>("lisi",20);
//名字只跟参数顺序有关,跟类型无关
(string Name,int Age,char Sex) per1 = ("lisi",18,'M');
(string Age,int Sex,char Name) per2 = per1;
Console.WriteLine(per2.Age); //lisi
Console.WriteLine(per2.Sex); //18
Console.WriteLine(per2.Name); //M
var person = ("lisi",20);
(string name,int age) = person;
Console.WriteLine(name); //lisi
Console.WriteLine(age); //20
var person = ("lisi",20);
var person1 = ("lisi",20);
Console.WriteLine(person.Equals(person1)); //True
总目录
C# 语法总目录