Who actually last decide what is the Generic Type?

前端 未结 6 1796
野性不改
野性不改 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 17:02

    There is no priority, both (a and b) should be the same, that is by design, T1 is resolved at compiling. If you change to dynamic, you just postpone type resolving to runtime and it will fail then instead at compiletime if the types are not the same. If you want them to be different, you need to introduce T3.

    Edit:

    The interesting part:

    Orange a = new Orange();
    Apple b = new Apple();
    string c = "Doh.";
    
    MyFunc(a,b,c);
    
    public static T2 MyFunc( T1 a, T1 b, T2 c) where T2 : class
    {
        return (a.ToString() + b.ToString() + c.ToString()) as T2;
    }     
    

    outputs:

    I am an orange. I am an apple. Doh.
    

    But this:

    dynamic a = new Orange();
    dynamic b = new Apple();
    string c = "Doh.";
    
    MyFunc(a,b,c);
    

    will throw:

    RuntimeBinderException: The best overloaded method match for 'UserQuery.MyFunc(UserQuery.Apple, UserQuery.Apple, string)' has some invalid arguments
    

    However it seems I really need to find a good book or resource about dynamic types in C# 4.0 to understand the magic happening here.

提交回复
热议问题