using System;
namespace TupleDemo
{
class Program
{
static void Main(string[] args)
{
//1、将元组赋值给单独声明的变量
(string country1, string capital1, double gdpPerCapita1) = ("Malawi", "lilongwe", 226.50);
Console.WriteLine($@"The poorest country in the world in 2017 was {country1},{capital1}:{gdpPerCapita1}");
//2、将元组赋给预声明的变量
string country2;
string capital2;
double gdpPerCapita2;
(country2, capital2, gdpPerCapita2) = ("Malawi", "lilongwe", 226.50);
Console.WriteLine($@"The poorest country in the world in 2017 was {country2},{capital2}:{gdpPerCapita2}");
//3、将元组赋给单独声明和隐式类型的变量
(var country3, var capital3, var gdpPerCapita3) = ("Malawi", "lilongwe", 226.50);
Console.WriteLine($@"The poorest country in the world in 2017 was {country3},{capital3}:{gdpPerCapita3}");
//4、将元组赋给单独声明和隐式类型的变量,但只用了一个var
var (country4, capital4, gdpPerCapita4) = ("Malawi", "lilongwe", 226.50);
Console.WriteLine($@"The poorest country in the world in 2017 was {country4},{capital4}:{gdpPerCapita4}");
//5、声明具名元组,将元组值赋给它,按名称访问元组项
(string Name, string Capital5, double GdpPerCapita) countryInfo = ("Malawi", "Lilongwe", 226.50);
Console.WriteLine($@"The poorest country in the world in 2017 was {countryInfo.Name},{countryInfo.Capital5}:{countryInfo.GdpPerCapita}");
//6、声明包含具名元组项的元组,将其赋值给隐式类型的变量,按名称访问元组
var countryInfo1 = (Name:"Malawi", Capital:"lilongwe", GdpPerCapita:226.50);
Console.WriteLine($@"The poorest country in the world in 2017 was {countryInfo1.Name},{countryInfo1.Capital}:{countryInfo1.GdpPerCapita}");
//7、将元组项未具名的元组赋给隐式类型的变量,通过项编号属性访问单独的元素
var countryInfo2 = ("Malawi", "lilongwe", 226.50);
Console.WriteLine($@"The poorest country in the world in 2017 was {countryInfo2.Item1},{countryInfo2.Item2}:{countryInfo2.Item3}");
//8、将元组项具名的元组赋给隐式类型的变量,但还是通过项目编号属性访问单独的元素
var countryInfo3 = (Name: "Malawi", Capital: "lilongwe", GdpPerCapita: 226.50);
Console.WriteLine($@"The poorest country in the world in 2017 was {countryInfo3.Item1},{countryInfo3.Item2}:{countryInfo3.Item3}");
//9、赋值时用下划线丢弃元组的一部分(弃元)
(string name, _,double gdpPerCapita) = ("Malawi", "Lilongwe", 226.50);
Console.WriteLine($@"The poorest country in the world in 2017 was {name},{gdpPerCapita}");
//10、通过变量和属性名推断元组项名
string country10 = "Malawi";
string capital10 = "Lilongwe";
double gdpPerCapita10 = 226.50;
var countryInfo10 = (country10, capital10, gdpPerCapita10);
Console.WriteLine($@"The poorest country in the world in 2017 was {countryInfo10.country10},{countryInfo10.capital10}:{countryInfo10.gdpPerCapita10}");
Console.ReadLine();
}
}
}