Who actually last decide what is the Generic Type?

前端 未结 6 1763
野性不改
野性不改 2021-01-02 16:01

I have this function

 public static T2 MyFunc( T1 a, T1 b, T2 c)
        {
            return c;
        }     

I\'m creatin

6条回答
  •  礼貌的吻别
    2021-01-02 16:46

    Who actually decide about the T1 type ? (p ? p2 ? )

    Isn't it obvious? Both of them. The types of p and p2 have to be compatible. Contrary to what other answers are saying, they don't have to be the same. The actual rule is that there has to be an implicit conversion from on of the types to the other.

    So, for example MyFunc("a", new object(), 5) is the same as MyFunc("a", new object(), 5), because string is implicitly convertible to object. As another example, MyFunc(42L, 42, 4) is the same as MyFunc(42L, 42, 4), because int is implicitly convertible to long.

    Also, there are cases where the ability to let the compiler infer the types is not just nice, it's necessary. Specifically, that happens when using anonymous types. For example MyFunc(new { p = "p" }, new { p = "p2" }, 5) can't be rewritten to specify the types explicitly.

提交回复
热议问题