如何通过实例详解深入理解.NET扩展方法的使用技巧和原理?
- 内容介绍
- 文章标签
- 相关推荐
本文共计1216个文字,预计阅读时间需要5分钟。
扩展方法有几个必要前提:- 扩展方法所在的类必须是静态类。- 扩展方法本身必须是静态方法。- 扩展方法参数中,对类型的扩展参数前必须加this关键字。- 扩展方法的基本数据类型。- 针对DateTime类型的处理。
扩展方法有几个必要前提:
- 扩展方法所在的类必须是静态类
- 扩展方法本身必须是静态方法
- 扩展方法参数中,对类型的扩展参数前必须加this关键字
扩展基本数据类型
针对DateTime类型写一个扩展方法。
public static class CalculateAge { public static int Age(this DateTime date, DateTime birthDate) { int birthYear = birthDate.Year; int currentYear = DateTime.Now.Year; if (birthYear >= currentYear) { throw new Exception("请输入正确的出生日期~~"); } else { return currentYear - birthYear - 1; } } }
客户端调用。
本文共计1216个文字,预计阅读时间需要5分钟。
扩展方法有几个必要前提:- 扩展方法所在的类必须是静态类。- 扩展方法本身必须是静态方法。- 扩展方法参数中,对类型的扩展参数前必须加this关键字。- 扩展方法的基本数据类型。- 针对DateTime类型的处理。
扩展方法有几个必要前提:
- 扩展方法所在的类必须是静态类
- 扩展方法本身必须是静态方法
- 扩展方法参数中,对类型的扩展参数前必须加this关键字
扩展基本数据类型
针对DateTime类型写一个扩展方法。
public static class CalculateAge { public static int Age(this DateTime date, DateTime birthDate) { int birthYear = birthDate.Year; int currentYear = DateTime.Now.Year; if (birthYear >= currentYear) { throw new Exception("请输入正确的出生日期~~"); } else { return currentYear - birthYear - 1; } } }
客户端调用。

