zoukankan      html  css  js  c++  java
  • 扩展方法用法整理

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

    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”;

  • 相关阅读:
    PostgreSQL管理工具:pgAdminIII
    PostgresQL7.5(开发版)安装与配置(win2003测试通过)
    让PosggreSQL运行得更好
    在.NET程序中使用PIPE(管道技术)
    在浏览网页过程中,单击超级链接无任何反应
    字符串转换
    数组初始化
    使用现有的COM
    后台服务程序开发模式(一)
    COM的四本好书
  • 原文地址:https://www.cnblogs.com/chunhui212/p/5902808.html
Copyright © 2011-2022 走看看