簡體   English   中英

模式匹配中的元組解構

[英]Tuple deconstruction in pattern matching

經過長時間的休息后,我正在查看 c# 中的新功能,並試圖了解泛型類型匹配的工作原理。 同時我想知道是否可以解構模式中的元組,例如:

string SendIt<T>(T p) => p switch
{
    ValueTuple<int, int> t => $"int point {t.Item1}, {t.Item2}", // <- this works
    (float x, float y)     => $"float point {x}, {y}",           // <- this doesn't
    _                      => $"dunno, type={typeof(T)}",
};

does not work的情況下,您試圖將完全未知的東西( T沒有任何約束)解構為兩個元素。 在這種情況下,編譯器將嘗試在static void Deconstruct<T>(this T val, out float x, out float y)中的某處進行搜索(無論如何,我無法想象這樣的 function 對於完全未指定的T會是什么樣子) . 所以,它不會編譯。

第一行(編譯)使用強制轉換,所以它只會在運行時處理所有內容(如果無法強制轉換,則不會將 go 放入分支中)

至於關於元組解構的問題,那么我們這里go - 只是修復了元組的聲明,明確地說它是一個元組,里面有兩個元素。

string SendIt<T1, T2>(Tuple<T1, T2> p) => p switch
{
    (float x, float y) => $"float point {x}, {y}", 
    _ => $"dunno, type={typeof(T)}",
};

Console.WriteLine(SendIt(Tuple.Create(2f,3f))); //float point 2, 3
Console.WriteLine(SendIt(Tuple.Create(2,"test"))); //dunno, type=System.Int32

我們還可以 go 進一步用 cast 方法,所以

string SendIt<T>(T p) => p switch
{
    ValueTuple<int, int> t => $"int point {t.Item1}, {t.Item2}", 
    Tuple<float, float>(float x, float y) => $"float point {x}, {y}", 
    _ => $"dunno, type={typeof(T)}",
};

Console.WriteLine(SendIt(ValueTuple.Create(1,2))); // int point 1, 2
Console.WriteLine(SendIt(Tuple.Create(1f,2f))); //float point 1, 2

Console.WriteLine(SendIt(Tuple.Create(1,2))); dunno, type=System.Tuple`2[System.Int32,System.Int32]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM