NET中的扩展方法

NET中的扩展方法

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

使用条件:

1.此方法必须是一个静态方法

2.此方法必须放在静态类中

3.此方法的第一个参数必须以this开头,并且指定此方法是扩展自哪个类型。

实例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ExtendFun
{
    public static class es
    {
        public static int ToInt(this string t)
        {
            int id;
            int.TryParse(t, out id);
            return id;
        }

        public static string IsOver(this string val)
        {
            return val + "";
            //一句话说完之后,加上句号。
        }
        public static string DateTimeToString1(this DateTime dt)
        {
            return dt.ToString("yyyy-mm-dd");
        }
        //DateTime类型扩展方法名为IsRange(判断是否在此时间范围内)
        public static int IsRange(this DateTime t, DateTime s, DateTime e)
        {
            if ((s - t).TotalSeconds > 0)
            {
                return -1;
            } if ((s - t).TotalSeconds < 0)
            {
                return 1;
            }
            return 0;

        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            //今天,我们就来看看传说中的扩展方法滴呀;
            //概念:扩展方法使你能够向现有类型“添加”方法,而无需创建新的派生类型,重新编译或改变原始类型;
            //这个是msdn上说的,简单的说,你可以向string int datarow datatable等类型的基础上增加一个或者多个方法;
            //string pwd="998168";
            //int val=pwd.ToInt();
            //这个大概就是 我们一个简单点额拓展方法了呢
            //string word = "I want to eat";
            //string val = word.IsOver();
            //这个大概就是对扩展方法的使用滴呀;

            DateTime now = DateTime.Now;
            string time = now.DateTimeToString1();  //然后我们就自动进行了扩展滴呀
            Console.WriteLine(time);
            Console.ReadLine();
        }
    }
}

 对一个类进行方法的扩展

原文地址:https://www.cnblogs.com/mc67/p/5066342.html