开发者

How to invoke Foo(this object o) instead of Foo(this T t) if they both exist?

How to inv开发者_如何学JAVAoke Display method extending object class?

static class Tools
{
    public static void Display<T>(this T t)
    {
        Console.WriteLine("generic: " + t.GetType());

    }

    public static void Display(this object o)
    {
        Console.WriteLine("object: " + o.GetType());
    }
}

class Program
{
    static void Main(string[] args)
    {
        int i = 100;


        // all  will invoke the generic version.
        Tools.Display<int>(i);
        i.Display();
        Tools.Display(i);

    }
}


I can't remember where in the standard it says it, but C# prefers to call the most specific overload. With generics, the generic version of the function will almost always take preference. So while an int is an object, it better fits the Display<T>(T) than Display(object), since the realization of the generic (Display<int>(int)) is an exact match. Add the fact that C# can figure out which type belongs in the T by itself and you see the behavior you're experiencing.

So, you must explicitly cast to an object to call the object version:

((object)i).Display();

Alternatively:

Tools.Display((object)i);

And you'll have a curious (but sensible) issue if you do:

object o = 5;
o.Display();
o.Display<object>();

This will call the object version in the first case and the generic one in the second. Fun times with parameters!


Since i is an int, the generic overload is a better match than the one taking an object. If you cast i to object, the non-generic version will be invoked.


The Display Method is redundant. You actually do not need both the methods together.

First let me explain why it always executed the Generic version over the other.

The C# compiler will find the best type-match for a method call. Here in all the calls, the generic method turns out to be the best match because generic version's type argument will always be the same as what given in the call.

so for Tools.Display(i) call compiler will prefer the generic version because that is the best option based on the type-match.

Even in the other calls, the type is inferred from the argument and hence the generic version is preferrably called over the other.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜