扩展方法的使用

来源:互联网 发布:邦家博士骗局揭秘 知乎 编辑:程序博客网 时间:2024/04/28 01:22
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace Test扩展方法
{
    static class StringExtend
    {
        public static bool IsEmal(this string s)//在static类中,在static方法中的第一个参数上加一个 this,就是对这个参数的类型的扩展。
        {
            if (s.Contains("@")) 
            { 
                return true;
            }
            else 
                return false;
        }
        public static string AddString(this string s,string str)//this必须加在第一个参数上面才能形成对第一个参数类型的扩展。
        {
            return s + str;
        }
    }

}


在main函数中调用

namespace Test扩展方法
{
    class Program
    {
        static void Main(string[] args)
        {
            string s = "123@qq.com";
            Console.WriteLine(s.IsEmal());
            Console.WriteLine(s.AddString("zzzz"));//带参数的扩展方法
            Console.ReadKey();
        }
    }
}

0 0
原创粉丝点击