Overloaded extension method is not being called

拟墨画扇 提交于 2019-12-11 03:22:58

问题


If we have a simple class like this one:

class MyClass
{
    public void DoSomething(object anObj)
    {
        Console.WriteLine("I am an Object: {0}", anObj);
    }

    public void DoSomething(string aStr)
    {
        Console.WriteLine("I am a String: {0}", aStr);
    }
}

And now we do this:

        var myClass = new MyClass();
        myClass.DoSomething("A message");

The output is "I am a String: some text"

Ok. That is fine. But if we have a "similar" overload with a extension method, for instance:

class MyClass
{
    public void DoSomething(object anObj)
    {
        Console.WriteLine("I am an Object: {0}", anObj);
    }
}

static class MyClassExtension
{
    public static void DoSomething(this MyClass myClass, string aStr)
    {
        Console.WriteLine("I am a String: {0}", aStr);
    }
}

And now we execute the same code than before:

        var myClass = new MyClass();
        myClass.DoSomething("some text");

The output is "I am an Object: some text"

Could someone explain this behaviour?.

I guess it is related with when the methods are assigned but I am missing something here. I will appreciate any clarification. Thanks


回答1:


Could someone explain this behaviour?

Sure - extension methods aren't considered until after the compiler has failed to find a normal instance method to call. They're not part of the normal candidate set. If you do something that would make it fail to compile with the normal instance method, then it will be taken into consideration. For example, you could add another parameter, or change the parameter type of the existing method:

public void DoSomething(int foo)

Or even call it using a named argument instead, to make it only match the extension method:

myClass.DoSomething(aStr: "some text");


来源:https://stackoverflow.com/questions/26885423/overloaded-extension-method-is-not-being-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!