在 .NET 4.0 中使用 .NET 4.5 中新增的特性(CallerMemberNameAttribute/CallerFilePathAttribute/CallerLineNumberAttribute)
2015-09-13 19:25
447 查看
介绍
标题中所说的三个特性 CallerMemberNameAttribute / CallerFilePathAttribute / CallerLineNumberAttribute 我们统称为调用者信息特性,正常情况下在 .NET Framework 4.0 中是无法使用的。因为这三个特性是 .NET Framework 4.5 中新增的。然而这三个特性的作用只是请求编译器在编译过程中进行代码的转换。使用示例
static void Main( string[] args ) { var productInfo = new ProductInfo(); productInfo.Name = "lumia"; productInfo.PropertyChanged(); Console.ReadKey( true ); } } public class ProductInfo { private string _name; public string Name { get { return this._name; } set { this._name = value; this.PropertyChanged(); } } public void PropertyChanged([CallerMemberName]string name = "", [CallerLineNumber]int line = 0, [CallerFilePath]string file = "") { Console.WriteLine("------------------------------------------------"); Console.WriteLine($"Name : {name}, \nLine : {line}, \nPath : {file}"); } }
注意上面标为橘红色的语句。运行时将自动填充这三个可选参数的值。开发过 WPF 的同学都知道这是多么的方便,不用显示指定参数名称。然而入我上面所说他不能在 .NET Framework 4.0 中使用,不过还好有办法。很简单,我们只需要自己定义这三个特性就可以了,代码如下。
namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] public class CallerMemberNameAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false )] public class CallerFilePathAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false )] public class CallerLineNumberAttribute : Attribute { } }
没有什么参数和成员在这三个特性里面。但要注意命名空间一定要与上面的一样。
相关文章推荐
- 递归实现数组全排列
- AudioManager(常用)解析
- CSS透明边框
- iOS地图开发
- 计算机图书
- CTreeCtrl
- 互联网、因特网及万维网之间的区别与联系
- 杭州电子科技大学acm--2011
- 8.30——9.4日随笔之一(面向对象)
- 文件复制
- WIN7下如何删除需要管理员权限才能删除的文件夹
- 数据结构学习1--基础知识
- 将文件中的数据读取,打印到控制台
- hdu 5437 Alisha’s Party
- js控制背景音乐播放
- Opencv+Kinect2.0 的环境配置和获取彩色图
- 移除HTML5 input在type="number"时的上下小箭头
- XSS绕过长度限制的两个Tips
- POJ 2000 Gold Coins
- linux 查找出包含某个字符串的所有文件的方法详解