zoukankan      html  css  js  c++  java
  • 扩展方法

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

    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);
            }
        }
    }
  • 相关阅读:
    @Value注解无法为static 变量赋值
    CloseableHttpClient方式配置代理服务器访问外网
    微信小程序上传图片
    centos7 无界面静默安装 oracle
    Linux安装配置JDK
    java导出Excel定义导出模板
    ECharts柱状图
    Java获取客户端真实IP
    Eclipse控制台输出log日志中文乱码
    $_SRRVER常用用法
  • 原文地址:https://www.cnblogs.com/yxcn/p/13606760.html
Copyright © 2011-2022 走看看