• 扩展方法用法整理


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

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

  • 相关阅读:
    一、用Delphi10.3模拟读取百度网页,并读取相关头部信息
    计算机语言发展史
    VMware workstation 14 安装 iOS虚拟机
    mysql-1
    linux网页资料链接
    Ubuntu常用命令大全
    搭建yum源
    CentOS7安装iptables防火墙
    nginx 第二课
    交换机
  • 原文地址:https://www.cnblogs.com/chunhui212/p/5902808.html
Copyright © 2020-2023  润新知