C# this扩展方法的使用

8 篇文章 0 订阅


扩展方法使您能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样进行调用。

C#扩展方法第一个参数指定该方法作用于哪个类型,并且该参数以 this 修饰符为前缀。


实例1、给string 类型增加一个Add方法,该方法的作用是给字符串增加一个字母a


       //必须是静态类才可以添加扩展方法
       Static class Program
       {
        static void Main(string[] args)
        {
            string str = "quzijing";
            //注意调用扩展方法,必须用对象来调用 
            string Newstr = str.Add();
            Console.WriteLine(Newstr);
            Console.ReadKey();
        }
        //声明扩展方法
        //扩展方法必须是静态的,Add有三个参数
        //this 必须有,string表示我要扩展的类型,stringName表示对象名
        //三个参数this和扩展的类型必不可少,对象名可以自己随意取如果需要传递参数,//再增加一个变量即可

        public static  string  Add(this string stringName)
        {
            return stringName+"a";
        }
}


实例2、为string扩展一个验证邮件类


(1)、扩展方法


using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Text.RegularExpressions;

 

//声明扩展方法的步骤:类必须是static,方法是static,

//第一个参数是被扩展的对象,前面标注this。

//使用扩展方法的时候必须保证扩展方法类已经在当前代码中using

namespace 扩展方法

{

    //扩展方法必须是静态的

    public static class StringHelper

    {

        //扩展方法必须是静态的,第一个参数必须加上this

        public static bool IsEmail(this string _input)

        {

            return Regex.IsMatch(_input, @"^\\w+@\\w+\\.\\w+$");

        }

        //带多个参数的扩展方法

        //在原始字符串前后加上指定的字符

        public static string Quot(this string _input, string _quot)

        {

            return _quot + _input + _quot;

        }

    }

}


(2)、使用方法


using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace 扩展方法

{

    class Program

    {

        static void Main(string[] args)

        {

            string _myEmail = "abc@163.com";

            //这里就可以直接使用string类的扩展方法IsEmail了

            Console.WriteLine(_myEmail.IsEmail());

            //调用接收参数的扩展方法

            Console.WriteLine(_myEmail.Quot("!"));

 

            Console.ReadLine();

        }

    }

}


文章转载自: C# this扩展方法    http://www.studyofnet.com/news/688.html


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值