[筆記] C# Tuple與ValueTuple的差異

比較Tuple與ValueTuple的差異範例

 

Tuple
void Main()
{
	Tuple<string, string, int, bool> goods 
	    = Tuple.Create("G01", "BlackTea", 20, true);
		
	Console.WriteLine(goods);
	
	//假設要取得第2個參數值
	Console.WriteLine(goods.Item2); 
}

ValueTuple
void Main()
{
	(string goodsId, string goodsName, int goodsPrice, bool hasStock) goods 
	    = (goodsId: "G01", goodsName: "BlackTea", goodsPrice: 20, hasStock: true);
		
	Console.WriteLine(goods);
	
	//假設要取得第2個參數值,有以下兩種方式
	Console.WriteLine(goods.Item2); 
	Console.WriteLine(goods.goodsName);
}

補充
//這樣寫回出現 無法將類型...隱含轉換成... 的錯誤
data.Select(x => new Tuple<TestClassDto, int>(x.Dto.TestClass, x.dataCount));

//需要幫它做轉換 補上ToValueTuple()
data.Select(x => new Tuple<TestClassDto, int>(x.Dto.TestClass, x.dataCount).ToValueTuple());

 

參考來源:

https://www.huanlintalk.com/2017/04/c-7-tuple-syntax.html

https://docs.microsoft.com/zh-tw/dotnet/csharp/tuples

https://docs.microsoft.com/zh-tw/dotnet/api/system.tuple?view=netframework-4.8