我一直在尋找 C# 中本地結構的替代方案,這在 C/C 中是可能的,但在 C# 中是不可能的。這個問題向我介紹了輕量級 System.ValueTuple 型別,它出現在 C# 7.0 (.NET 4.7) 中。
假設我有兩個以不同方式定義的元組:
var book1 = ("Moby Dick", 123);
(string title, int pages) book2 = ("The Art of War", 456);
兩個元組都包含兩個元素。的型別Item1是System.String,并且 的型別Item2在System.Int32兩個元組中。
如何確定元組變數中的元素數量?你可以使用類似的東西來迭代這些元素foreach嗎?
快速閱讀有關 System.ValueTuple 的官方檔案似乎沒有資訊。
uj5u.com熱心網友回復:
是的,您可以通過以下回圈遍歷專案for:
var tuple = ("First", 2, 3.ToString());
ITuple indexableTuple = (ITuple)tuple;
for (var itemIdx = 0; itemIdx < indexableTuple.Length; itemIdx )
{
Console.WriteLine(indexAbleTuple[itemIdx]);
}
- 訣竅是您需要明確地將您的轉換
ValueTuple為ITuple - 該介面公開
Length和索引運算子
ITuple駐留在System.Runtime.CompilerServices命名空間內。
uj5u.com熱心網友回復:
我想你正在尋找的是這樣的:
public void Run(string[] args)
{
Tuple<string, string, int> myTuple = new Tuple<string, string, int>("1st", "2nd", 3);
LoopThroughTupleInstances(myTuple);
}
private static void LoopThroughTupleInstances(System.Runtime.CompilerServices.ITuple tuple)
{
for (int i = 0; i < tuple.Length; i )
{
Console.WriteLine($"Type: {tuple[i].GetType()}, Value: {tuple[i]}");
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/430863.html
上一篇:如何獲取多行字串
