• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
PowerCoder
博客园    首页    新随笔    联系   管理    订阅  订阅

C#中如果类的扩展方法和类本身的方法签名相同,那么会优先调用类本身的方法

新建一个.NET Core项目,假如我们有如下代码:

using System;

namespace MethodOverload
{

    static class DemoExtension
    {
        public static int GetNumber(this Demo d,int i)
        {
            Console.WriteLine("DemoExtension GetNumber was called!");
            return i;
        }
    }


    class Demo
    {
        public int GetNumber(int i)
        {
            Console.WriteLine("Demo GetNumber was called!");
            return i;
        }
    }


    class Program
    {
        static void Main(string[] args)
        {
            Demo demo = new Demo();

            demo.GetNumber(100);

            Console.WriteLine("Press any key to end...");
            Console.ReadLine();
        }
    }
}

 

我们可以在VisualStudio中看到demo.GetNumber方法有一个重载:

一个是Demo类中定义的GetNumber方法,还有个是DemoExtension类中定义的GetNumber扩展方法,那么我们在调用demo.GetNumber(100)时,到底调用的哪个方法呢?

执行结果如下:

可以看到是Demo类中定义的GetNumber方法被调用了,所以如果说有扩展方法和类本身的方法签名相同,C#会优先调用类本身的方法。

 

假如现在我们注释掉Demo类中定义的GetNumber方法:

using System;

namespace MethodOverload
{

    static class DemoExtension
    {
        public static int GetNumber(this Demo d,int i)
        {
            Console.WriteLine("DemoExtension GetNumber was called!");
            return i;
        }
    }


    class Demo
    {
        //public int GetNumber(int i)
        //{
        //    Console.WriteLine("Demo GetNumber was called!");
        //    return i;
        //}
    }


    class Program
    {
        static void Main(string[] args)
        {
            Demo demo = new Demo();

            demo.GetNumber(100);

            Console.WriteLine("Press any key to end...");
            Console.ReadLine();
        }
    }
}

现在执行结果如下:

这次我们看到调用的就是DemoExtension类中定义的GetNumber扩展方法了

 

posted @ 2018-10-17 17:07  PowerCoder  阅读(738)  评论(1)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3