代码改变世界

扩展方法

2020-09-03 11:48  石吴玉  阅读(600)  评论(0编辑  收藏  举报

一、扩展方法必须满足的前提

1.方法所在类必须是静态的

2.方法本身也必须是静态的

3.方法的第一个参数必须是要扩展的那个类型,且必须带有 this关键字

 

二、优势

可以在不继承,不修改原类的情况下,添加新方法

 

三、限制

1.虽然是静态类的静态方法,但要由被扩展类型的对象调用。

2.如果扩展类与被扩展类由相同的签名,则扩展类的方法会被覆盖,不会执行。

3.扩展方法不能访问被扩展方法的私有成员。

 

四、案例

编写扩展类

using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace TestExtension
{
    public static class Extension
    {
        public static void AddTest(this IServiceCollection services)
        {
            string temp = "Hello Extension";
        }
    }
}

调用扩展类的扩展方法

namespace TestExtension
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            //扩展方法被this参数的对象调用
            services.AddTest();
            Extension.AddTest(services);
        }
    }
}