【已更新最新开发文章,点击查看详细】

System.Runtime.CompilerServices 命名空间中定义的调用方信息特性:

特性 描述 类型
CallerFilePathAttribute 这是编译时的文件路径。 String
CallerLineNumberAttribute 源文件中调用方法的行号。 Integer
CallerMemberNameAttribute 成员名称。 String

示例

每次调用 TraceMessage 方法时,调用方信息将替换为可选参数的变量。

 1 public void DoProcessing()
 2 {
 3     TraceMessage("Something happened.");
 4 }
 5 
 6 public void TraceMessage(string message,
 7                          [System.Runtime.CompilerServices.CallerMemberName] string memberName = "",
 8                          [System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = "",
 9                          [System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0)
10 {
11     System.Diagnostics.Trace.WriteLine("message: " + message);
12     System.Diagnostics.Trace.WriteLine("member name: " + memberName);
13     System.Diagnostics.Trace.WriteLine("source file path: " + sourceFilePath);
14     System.Diagnostics.Trace.WriteLine("source line number: " + sourceLineNumber);
15 }
16 
17 // 输出结果:
18 //  message: Something happened.
19 //  member name: DoProcessing
20 //  source file path: c:\Visual Studio Projects\CallerInfoCS\CallerInfoCS\Form1.cs
21 //  source line number: 31

备注

不能将调用方信息特性应用于未指定为可选的参数。

相反,它们会在忽略此参数时影响传入的默认值。

StackTrace 属性的结果不同,这些结果不受模糊处理的影响。

你可显式提供可选参数来控制调用方信息或隐藏调用方信息。

成员名称

此好处对于以下任务特别有用:

  • 使用跟踪和诊断例程。

  • 如果没有 CallerMemberName 特性,则必须将属性名称指定为文本。

以下图表显示在使用 CallerMemberName 特性时返回的成员名称。

调用发生中 成员名称结果
方法、属性或事件 从中发起调用的方法、属性或事件的名称。
构造函数 字符串“.ctor”
静态构造函数 字符串“.cctor”
析构函数 字符串“Finalize”
用户定义的运算符或转换 为成员生成的名称,例如,“op_Addition”。
特性构造函数 如果该特性是成员中的任何元素(如参数、返回值或泛型参数),则此结果是与该元素关联的成员的名称。
无包含的成员(例如,程序集级别或应用于类型的特性) 可选参数的默认值。
 
【已更新最新开发文章,点击查看详细】

相关文章:

  • 2022-01-01
  • 2022-01-07
  • 2022-01-07
  • 2022-01-07
  • 2022-01-07
  • 2021-11-03
  • 2021-08-03
猜你喜欢
  • 2021-10-30
  • 2021-11-11
  • 2021-12-06
  • 2021-05-22
  • 2022-01-02
  • 2022-01-21
相关资源
相似解决方案