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

    扩展方法使您能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。

    扩展方法就相当于一个马甲,给一个现有类套上,就可以为这个类添加其他方法了.

    马甲必须定义为static类型,下面实例给string类型添加一个add(string)方法,相当于字符串拼接.

    static class majia
    {
        //me表示给哪个类型穿马甲,this string参数表示给string类型穿马甲
        //this修饰的参数必须作为第一个参数
        static public string add(this string me, string s)
        {
            return me + s;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("haha".add("weidiao"));
        }
    }

    输出为"hahaweidiao"

    注意:

    (1)this修饰的参数必须作为第一个参数

    (2)马甲方法必须定义为静态类型

    (3)马甲类必须定义为静态类型

    (4)马甲方法可以有多个参数

    还可以让马甲方法调用马甲类的其他东西,比如:

    static class majia
    {
        static int x = 0;
        //me表示给哪个类型穿马甲,this string参数表示给string类型穿马甲
        //this修饰的参数必须作为第一个参数
        static public string add(this string me, string s)
        {
            return me + s+(x++);
        }
    }

    这样就可以每次拼接完字符串后再加上一个int数字表示这个函数被调用过多少次.

  • 相关阅读:
    C#的集合类(二)Hashtable、SortedList、Dictionary
    下载文件-JavaScript
    ASP.NET(C#)图片加文字、图片水印
    C# DataTable 互转 List<T>
    C# 将 DataTable 转 List<T>、首行转 T
    C# 金额转中文大写
    监听端口守护进程
    数据库操作的九大步骤
    日志方法
    sqlserver 查找所有子级
  • 原文地址:https://www.cnblogs.com/weiyinfu/p/6035829.html
Copyright © 2011-2022 走看看