介绍

标题中所说的三个特性 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 = , [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
{ }
}

没有什么参数和成员在这三个特性里面。但要注意命名空间一定要与上面的一样。

最新文章

  1. python之初级学习
  2. 《TCP/IP详解卷1:协议》第1章 概述-读书笔记
  3. HTML学习之Web存储(五)
  4. Arduino101学习笔记(二)—— 一些注意的语法点
  5. js的小效果-图片放大镜效果
  6. 《驾驭Core Data》 第一章 Core Data概述
  7. Collections的排序之一(Java)
  8. (六)C语言之typedef详解
  9. 【转】Tomcat配置文件入门
  10. java内存模型7-处理器内存模型
  11. Codefoces 723B Text Document Analysis
  12. h5的input的required使用中遇到的问题
  13. Linux Debugging(六): 动态库注入、ltrace、strace、Valgrind
  14. CVE-2018-19386:SolarWinds数据库性能分析器中反射的XSS
  15. Qt License 解读
  16. CSS3新增特性及知识学习线路
  17. Javascript高级编程学习笔记(52)—— DOM2和DOM3(4)元素大小
  18. Visual Studio 产品密钥
  19. PAT A1124 Raffle for Weibo Followers (20 分)——数学题
  20. OOM之类、对象、实例、实体之辨析

热门文章

  1. makefile小例子
  2. H5摇一摇遇到的问题
  3. [Maven]Maven详解
  4. fuser 命令小结
  5. WinRAR压缩操作帮助类
  6. SQL时间相关
  7. Linux 命令与文件的搜寻
  8. 在windows编译MariaDB
  9. 3、NAT
  10. Struts2从一个action转到另一个action的两种方法