虛虛實實,亦假亦真的 ValueTuple,絕對能眩暈你

一:背景

1. 講故事

前幾天在寫一個api接口,需要對衣物表進行分頁查詢,查詢的output需要返回兩個信息,一個是 totalCount,一個是 clothesList,在以前我可能需要封裝一個 PagedClothes 類,如下代碼:


    public class PagedClothes
    {
        public int TotalCount { get; set; }
        public List<Clothes> ClothesList { get; set; }
    }

    static PagedClothes GetPageList()
    {
        return new PagedClothes()
        {
            TotalCount = 100,
            ClothesList = new List<Clothes>() { }
        };
    }

在 C# 7.0 之后如果覺得封裝一個類太麻煩或者沒這個必要,可以用快餐寫法,如下代碼:


    static (int, List<Clothes>) GetPageList()
    {
        return (10, new List<Clothes>() { });
    }

這里的 (int, List<Clothes>) 是什么意思呢? 懂的朋友看到 (x,y) 馬上就會想到它是 .NET 引入的一個新類:ValueTuple,接下來的問題就是真的是ValueTuple嗎? 用ILSpy 看看 IL 代碼:


    .method private hidebysig static 
        valuetype [System.Runtime]System.ValueTuple`2<int32, class [System.Collections]System.Collections.Generic.List`1<class ConsoleApp2.Clothes>> GetPageList () cil managed 
    {
        IL_0000: nop
        IL_0001: ldc.i4.s 10
        IL_0003: newobj instance void class [System.Collections]System.Collections.Generic.List`1<class ConsoleApp2.Clothes>::.ctor()
        IL_0008: newobj instance void valuetype [System.Runtime]System.ValueTuple`2<int32, class [System.Collections]System.Collections.Generic.List`1<class ConsoleApp2.Clothes>>::.ctor(!0, !1)
        IL_000d: stloc.0
        IL_000e: br.s IL_0010

        IL_0010: ldloc.0
        IL_0011: ret
    } // end of method Program::GetPageList

GetPageList 方法的 IL 代碼可以很容易的看出方法返回值和return處都有 System.ValueTuple 標記,<font color="red">從此以后你可能就會以為 (x,y) 就是 ValueTuple 的化身 </font>,是吧,問題就出現(xiàn)在這里,這個經(jīng)驗靠譜嗎?

二:(x,y) 真的是 ValueTuple 的化身嗎

為了去驗證這個經(jīng)驗是否靠譜,我需要舉幾個例子:

1. (x,y) 接收方法返回值時是 ValueTuple 嗎

為了更加清楚的表述,先上代碼:

        (int totalCount, List<Clothes> orders) = GetPageList();

        static (int, List<Clothes>) GetPageList()
        {
            return (10, new List<Clothes>() { });
        }

現(xiàn)在已經(jīng)知道當 (x,y) 作為方法返回值的時候在IL層面會被化作 ValueTuple,那 (x,y) 作為接受返回值的時候又是什么意思呢? 還會和 ValueTuple 有關系嗎? 為了去驗證,可以用反編譯能力弱點的 dnspy 去看看反編譯后的代碼:

從圖中可以看出,當用 (x,y) 模式接收的時候,貌似就是實現(xiàn)映射賦值 或者 叫做拆解賦值,是不是有一點模糊,這個 (x,y) 貌似和 ValueTuple 有關系,又貌似和 ValueTuple 沒關系,不過沒關系,繼續(xù)看下一個例子。

2. (x,y) 在 foreach 迭代中是 ValueTuple 嗎

(x,y) 也可以出現(xiàn)在 foreach 中,相信第一次看到這么玩還是有一點吃驚的,如下代碼:


        var dict = new Dictionary<int, string>();

        foreach ((int k, string v) in dict)
        {
        }

接下來繼續(xù)用 dnspy 反編譯一下:

我去,這回就清晰了,從圖中可以看出,我寫的 (x,y) 壓根就沒有 ValueTuple 的影子,說明在這個場景下兩者并沒有任何關系,也就是說同樣是 (x,y) ,放在不同位置具有不同的表現(xiàn)形式,這就很讓人琢磨不透了, 可能有些朋友不死心,想看一下 Deconstruct 到底干了什么,知道的朋友應該明白這個新玩法叫做解構方法,繼續(xù)看代碼:


    public readonly struct KeyValuePair<TKey, TValue>
    {
        private readonly TKey key;
        private readonly TValue value;

        public void Deconstruct(out TKey key, out TValue value)
        {
            key = Key;
            value = Value;
        }
    }

有些抬杠的朋友會發(fā)現(xiàn)一個規(guī)律,貌似 (x,y) 放在賦值語句的左邊都和 ValueTuple 沒有任何關系,放在右邊可能會有奇跡發(fā)生,那到底是不是這樣呢? 繼續(xù)硬著頭皮舉例子唄。

3. (x,y) 放在賦值語句的右邊是 ValueTuple 嗎


    public class Point
    {
        public int X { get; set; }
        public int Y { get; set; }

        public Point(int x, int y)
        {
            (X, Y) = (x, y);
        }
    }

嘿嘿,看這句: (X, Y) = (x, y) 里的 (x,y) 是 ValueTuple 的化身嗎? 我猜你肯定是懵逼狀態(tài),是吧,亦真亦假,虛虛實實,證據(jù)還是繼續(xù)反編譯看唄。

我去,又是和 ValueTuple 一點關系都沒有,啥玩意嘛,亂七八糟的,莫名其妙。

三: 總結

說 (x,y) 是元組吧,放在 return 中就變成了 ValueTuple ,說 (x,y) 不是元組吧,放在其他處還真就不是的,是不是很疑惑,為了更加形象,在 Point 中再增加一個 Test 方法,對照一下源碼和反編譯的代碼:


    //原始的:
    public class Point
    {
        public int X { get; set; }
        public int Y { get; set; }

        public Point(int x, int y)
        {
            (X, Y) = (x, y);
        }

        public (int x, int y) Test()
        {
            return (X, Y);
        }
    }

    //反編譯的:
    public class Point
    {
        public int X { get; set; }
        public int Y { get; set; }

        public Point(int x, int y)
        {
            this.X = x;
            this.Y = y;
        }

        [return: TupleElementNames(new string[]
        {
            "x",
            "y"
        })]
        public ValueTuple<int, int> Test()
        {
            return new ValueTuple<int, int>(this.X, this.Y);
        }
    }

反正我已經(jīng)惱火了,就這樣吧,少用經(jīng)驗推理,多用工具挖一挖,這樣才靠譜!

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容