无名 发表于 2022-5-8 17:02:49

【LSP】虚虚实实,亦假亦真的 ValueTuple,绝对能眩晕


http://cdn.u1.huluxia.com/g4/M01/65/3C/rBAAdl91PYuAPCK9AACt4WdlvYs278.jpg
一:背景
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.ValueTuple`2<int32, class 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.Generic.List`1<class ConsoleApp2.Clothes>::.ctor()
                IL_0008: newobj instance void valuetype System.ValueTuple`2<int32, class 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 去看看反编译后的代码:

http://cdn.u1.huluxia.com/g4/M01/65/3C/rBAAdl91PYuAeI5EAABjh5EQKbM570.png

从图中可以看出,当用 (x,y) 模式接收的时候,貌似就是实现映射赋值 或者 叫做拆解赋值,http://cdn.u1.huluxia.com/g4/M01/65/3C/rBAAdl91PYyAZI6DAAByCk-Amvk682.png
http://cdn.u1.huluxia.com/g4/M01/65/3C/rBAAdl91PY2AG3lqAAM1uS3kbyI269.jpg
页: [1]
查看完整版本: 【LSP】虚虚实实,亦假亦真的 ValueTuple,绝对能眩晕