未调用重载的扩展方法 [英] Overloaded extension method is not being called

查看:54
本文介绍了未调用重载的扩展方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们有一个像这样的简单类:

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);
    }
}

现在我们这样做:

        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

推荐答案

有人可以解释这种行为吗?

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");

这篇关于未调用重载的扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆