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);
            }
        }
    }
  • 相关阅读:
    Centos7 关闭防火墙
    Linux下磁盘挂载
    Sqlserver游标复习
    Redis-benchmark测试Redis性能
    将treeview控件内容导出图片
    使用redis进行消息推送
    web性能优化系列之网站瓶颈识别
    SqlServer时间格式化
    PHP二位数组/多维数组 根据某个键值排序
    VIM Taglist + ctags
  • 原文地址:https://www.cnblogs.com/yxcn/p/13606760.html
Copyright © 2011-2022 走看看