扩展方法用法整理

扩展方法貌似平时很少用,平时基本都是用静态方法,其实静态方法也挺方便的。

class Program
    {
        static void Main(string[] args)
        {
            var p = new Person() { BirthTime = DateTime.Parse("1990-07-19") };
            var age = p.GetAge();//扩展方法调用起来更顺眼
            age = ExtensionClass.GetAge2(p);//静态方法调用
            Console.ReadKey();
        }
    }

    public static class ExtensionClass//注意扩展方法的类不能放到Program类里面,这样扩展方法就会报错
    {
        public static int GetAge2(Person person)//静态方法
        {
            if (person.DeathTime.HasValue)
                return (person.DeathTime.Value - person.BirthTime).Days / 365;
            else
                return (DateTime.Now - person.BirthTime).Days / 365;
        }

        public static int GetAge(this Person person)//扩展方法
        {
            if (person.DeathTime.HasValue)
                return (person.DeathTime.Value - person.BirthTime).Days / 365;
            else
                return (DateTime.Now - person.BirthTime).Days / 365;
        }
    }

    public class Person
    {
        public DateTime BirthTime { get; set; }
        public DateTime? DeathTime { get; set; }
    }

上面所有的都只是扩展方法的附加用处,扩展方法真正的威力是为Linq服务的(主要体现于IEnumerable和IQueryable)。下面简单列举个例子:

例:

        public static IList<T> MyWhere<T>(this IList<T> list, Func<T, bool> func)
        {
            List<T> newList = new List<T>();
            foreach (var item in list)
            {
                if (func(item))
                    newList.Add(item);
            }
            return newList;
        }

总结静态方法的定义规则:静态类里面命名静态方法,方法(扩展方法)第一个参数(被扩展的类型)前面加“this”;

时间: 2024-08-08 01:25:25

扩展方法用法整理的相关文章

扩展方法用法及其原理和注意事项

前言 一直以来尤其像C#一些常见的语法,本人更愿意去探讨其内部实现的原理,为什么要这么做呢?只是为了当我真正在开发中运用语法的时候不会因为犯常识性错误或者说因为一些注意事项未曾注意到而耽误一些无谓的时间,同时也能理解的更深入而不是仅仅停留在表面(或许理解也不是太透).(当然本人能力有限,太高深的东西必定是研究不明白了,也只有这能力了). 概念 扩展方法使你能够向现有类型“添加”方法,而无需创建新的派生类型.重新编译或以其他方式修改原始类型. 扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例

[原创]扩展方法基本用法

前言 首先我们看看msdn上面的解释:扩展方法使你能够向现有类型“添加”方法,而无需创建新的派生类型.重新编译或以其他方式修改原始类型. 其实说白了就是微软那班哥们写好的类库,我们无法修改,但是我们可以给这些类库通过一种方式添加我们的一些方法. 1.0 扩展方法应用场景 DateTime now = DateTime.Now; //1.0 将now格式化成yyyy-MM-dd 输出 string fmtstr = now.Tostring("yyyy-MM-dd");//2.0 将no

SQL 系统存储过程用法整理

---------------------------------------------------------------------------------- -- Author : htl258(Tony) -- Date   : 2010-07-06 23:13:19 -- Version: Microsoft SQL Server 2008 (RTM) - 10.0.1600.22 (Intel X86) --          Jul  9 2008 14:43:34 --    

泛型List集合转化为DateTable的扩展方法

文章出处:http://www.codeproject.com/Tips/867866/Extension-Method-for-Generic-List-Collection-to-Da 这段代码是能够帮助你把泛型集合List转出成DataTable的扩展方法. 背景: 不知道你是否知道这个扩展方法,但是你可以不做任何修改的去使用下面这个类的代码. 使用代码:   using System; using System.Collections.Generic; using System.Comp

List扩展方法汇总(仅备注)

不管在c/s还是b/s的c#语言开发程序中,经常会用到List的扩展方法,尤其在json格式的数据和服务端交互越来越流行,很多时候总是在开发使用到的时候才去搜索有些扩展方法或者linq的用法,在这里,我们只是做一个备注 因为linq没有必要系统的学习,我们只要简单的在list的扩展会使用即可,至少我只这么认为的 本文没有任何技术性,只是备注list或者list泛型的扩展方法,不至于在您不熟悉但是又使用到的时候到处搜索 1 public sealed class Employee 2 { 3 pu

Extension Methods(扩展方法)

在 OOPL 中,有静态方法.实例方法和虚方法,如下: public sealed class String { public static bool  IsNullOrEmpty(string s) { // ... } public string Replace(string old, string new) { // ... } } public abstract class Stream { public virtual void WriteByte(byte value) { // .

ASP.Net string 类的扩展方法 [转]

string 类的扩展方法列表(基本相同于 IEnumerable<T> 接口的成员列表): Aggregate<>     //累加 All<>        //是否都满足条件 Any<>        //是否有一个满足条件 AsEnumerable<>  // AsParallel<>    // AsQueryable<>    // Average<>      //平均值 Cast<>

MVc分页【关于使用扩展方法实现MVc分页】

近期对MVc自定义分页作了一下小研究下面把他记下来 下述代1,2,3里面的代码可以直接拷贝,4以后的根据情况自己选定 1.在后台任写如下的扩展方法(任一类库都可以,但是用时得引用命名空间) // 添加using System.Web; using System.Web.Mvc; 引用,找不到可以从MVC层拷贝 namespace System.Web.Mvc.Html // 注意一定要把类的命名空间写成System.Web.Mvc.Html { public static class PageE

c#之有参和无参构造函数,扩展方法

例如在程序中创建 Parent类和Test类,在Test有三个构造函数,parent类继承Test类,那么我们可以在Test类自身中添加 扩展 方法吗? 答案:是不可以的.因为扩展方法必须是静态的,且静态方法是不存在构造函数的. 先看一段代码: public class Test { public Test() { Console.WriteLine("这是无参的构造函数"); } public Test(string name) { Console.WriteLine(string.