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数字表示这个函数被调用过多少次.

  • 相关阅读:
    各种数字证书区别
    微信支付前端对接流程
    ts笔记 流动类型
    支付宝支付前端对接流程
    ts笔记索引签名
    [翻译]Selenium API 命令和操作(JAVA)
    玩一玩yolo目标检测
    快速上手MyBatis
    Swift快速入门
    Windows远程桌面后不能粘贴问题处理
  • 原文地址:https://www.cnblogs.com/weiyinfu/p/6035829.html
Copyright © 2011-2022 走看看