带接口的扩展方法

时间:2014-01-01 10:09:20

标签: c# extension-methods

我有以下界面

 public interface IMyInterface
    {
        void MethodB();
    }

我有以下扩展类:

public static class Extension
    {
        public static void MethodA(this IMyInterface myInterface, int i)
        {
            Console.WriteLine("Extension.MethodA(this IMyInterface myInterface, int i)");
        }

        public static void MethodA(this IMyInterface myInterface, string s)
        {
            Console.WriteLine("Extension.MethodA(this IMyInterface myInterface, string s)");
        }


        public static void MethodB(this IMyInterface myInterface)
        {
            Console.WriteLine("Extension.MethodB(this IMyInterface myInterface)");
        }
    }

我有以下课程:

class B : IMyInterface
    {
        public void MethodB()
        {
            Console.WriteLine("B.MethodB()");
        }

        public void MethodA(int i)
        {
            Console.WriteLine("B.MethodA(int i)");
        }
    }

在我的节目中,我有:

class Program
{
    static void Main(string[] args)
    {
        B b = new B();
        b.MethodA(7);
        b.MethodB();
        Console.ReadLine();
    }
}

// Output strings in console of above program

B.MethodB()&  B.MethodA(int i)

我的问题:从MSDN,我了解如果扩展方法与类型

中定义的方法具有相同的签名,则永远不会调用它

当我按b时,为什么没有显示MethodA(此IMyInterface myInterface,字符串s)。在我的程序?由于B类缺少一个带有签名MethodA(字符串s)的方法,MethodA(这个IMyInterface myInterface,字符串s)应该显示正确吗?但事实并非如此。

2 个答案:

答案 0 :(得分:2)

它出现了。由于“B类”具有相同名称的方法,因此“MethodA(此IMyInterface myInterface,string s)”方法将显示为“MethdodA()”的重载。 见下图。

enter image description here

答案 1 :(得分:1)

您是否引用了您的扩展类(使用“扩展类的命名空间”)?您需要在任何地方添加此指令。

相关问题