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

    通常我们都在使用.net自带类库或者第三方类库,有时候我们无法查看他们的代码,但是我们需要一些新的功能,这个时候我们就可以自己去定义一些自己想要的方法,就是扩展方法。


    扩展方法要求:
    1.必须是定义在静态类中的静态方法;
    2.第一个参数的类型是要扩展的类型;
    3.第一个参数需要添加this关键字以标识其为扩展方法。
    说明: 第3步中必须要有this关键字标识其为扩展方法,当我们想使用该扩展方法时,必须是一个对象来调用该方法,那么该对象必须是属于this关键字后引用的对象。


    Demo示例:
    1.最简单的扩展方法,string类扩展一个固定返回数据的扩展方法:

    	public static class MyString
        {
            public static string ReturnString(this string s)
            {
                return "string类的扩展方法ReturnString";
            } 
        }
        
    	public  static void Main(string[] args)
        {
            string str = "";
            string result = str.ReturnString();
    	}
    

    2.使用自定义类为扩展类型,为其添加一个扩展方法:

    	//自定义博客类
    	public class Blog
        {
            public string RenName(string name)
            {
                return name;
            }
        }
      
       //偷懒一点,直接在MyString类中加上一个返回博客名的扩展方法
      	public static class MyString
        {
            public static string AddBlogName(this Blog blog,string name)
            {
                string ResName =blog.RenName(name)+"的博客";
                return ResName;
            }
        }
        
    	//此时我们想使用“返回博客名的扩展方法”,应该先有一个扩展属性Blog的对象,才可以去调用
    	public  static void Main(string[] args)
        {
            Blog blog = new Blog();
            string blogName = blog.AddBlogName("小龙人");  //小龙人的博客
    	}
    

    3.在lambda表达式中对集合有一个where方法,再此我们针对其写一个MyWhere扩展方法:

    	//依然写在MyString类中了
    	public static class MyString
        {     
            public static List<int> MyWhere(this List<int> list,Func<int,bool> func)
            {
                List<int> newList = new List<int>();
                foreach (int i in list)
                {
                    if (func(i))
                    {
                        newList.Add(i);
                    }
                }
                return newList;
             }
         }
    
    	public static void Main(string[] args)
         {
             List<int> list = new List<int> { 3, 7, 2, 1, 8, 15, 99 };
             List<int> newList = list.MyWhere(a => a > 5);
         }
    

    到这里结束,不足之处,望指出。
    源码:https://github.com/wangqilong1225/C-Sharp-Test/tree/master/ExtendMethodDemo

  • 相关阅读:
    Windows下MySQL数据库备份脚本(二)
    pt-query-digest用法
    pt-online-schema-change 实例
    pt-kill使用
    pt-find 使用实例
    利用pt-deadlock-logger监控死锁
    pt-fifo-split使用
    bash{} 方法总结
    python psutil 模块
    Zabbix的安装与部署---问题处理(php65.6.28 mysqli 报错误 处理)
  • 原文地址:https://www.cnblogs.com/wangqilong/p/12540371.html
Copyright © 2011-2022 走看看