开发者

Why does this static factory method involving implied generic types, work?

开发者 https://www.devze.com 2022-12-13 13:13 出处:网络
Consider public class Tuple<T1, T2> { public Tuple(T1 v1, T2 v2) { V1 = v1; V2 = v2; } public T1 V1 { get; set; }

Consider

public class Tuple<T1, T2>
{
    public Tuple(T1 v1, T2 v2)
    {
        V1 = v1;
        V2 = v2;
    }

    public T1 V1 { get; set; }
    public T2 V2 { get; set; }
}

public static class Tuple
{
    // MAGIC!!
    public static Tuple<T1, T2> New<T1, T2>(T1 v1, T2 v2)
    {
        return new Tuple<T1, T2>(v1, v2);
    }
}

Why does the part labeled "MAGIC" in the above work? It allows syntax like Tuple.New(1, "2") instead 开发者_运维知识库of new Tuple<int, string>(1, "2"), but ... how and why?

Why do I not need Tuple.New<int,string>(1, "2") ??


This is called generic type inference and it works for generic methods only. You can pass instances of whatever types you want as the arguments to New and the compiler infers that you mean to return the particular generic Tuple that matches the arguments like Tuple<int, string>...


This is "Type Inference". See a great article here for details.


What is magic about it? You have two types, one that accepts generic type parameters and one that does not. They share the same name but they are not the same type. Try renaming one of them and see if it makes a little more sense to you.

/Klaus


C# Compiler automatically infer type and compile your

Tuple.New(1, "2")

to

Tuple.New<int,string>(1, "2") 
0

精彩评论

暂无评论...
验证码 换一张
取 消