天天看點

虛虛實實,亦假亦真的 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

标記,從此以後你可能就會以為 (x,y) 就是 ValueTuple 的化身 ,是吧,問題就出現在這裡,這個經驗靠譜嗎?

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

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

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

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

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

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

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

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

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

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

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

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

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

           

接下來繼續用 dnspy 反編譯一下:

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

我去,這回就清晰了,從圖中可以看出,我寫的 (x,y) 壓根就沒有 ValueTuple 的影子,說明在這個場景下兩者并沒有任何關系,也就是說同樣是 (x,y) ,放在不同位置具有不同的表現形式,這就很讓人琢磨不透了, 可能有些朋友不死心,想看一下

Deconstruct

到底幹了什麼,知道的朋友應該明白這個新玩法叫做解構方法,繼續看代碼:

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;
        }
    }

           

有些擡杠的朋友會發現一個規律,貌似 (x,y) 放在指派語句的左邊都和 ValueTuple 沒有任何關系,放在右邊可能會有奇迹發生,那到底是不是這樣呢? 繼續硬着頭皮舉例子呗。

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 的化身嗎? 我猜你肯定是懵逼狀态,是吧,亦真亦假,虛虛實實,證據還是繼續反編譯看呗。

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

我去,又是和 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);
        }
    }

           

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

如您有更多問題與我互動,掃描下方進來吧~

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