调用方信息

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

 

特性

说明

类型

CallerFilePathAttribute

这是文件路径在编译时。

String

CallerLineNumberAttribute

在调用方法的源文件中的行号。

Integer

CallerMemberNameAttribute

Member Names 本主题后面

String

 
 
 
 
 
 
 
 
 
 
 

TraceMessage 方法,信息将替换为可选参数的参数的调用方。

 1 // using System.Runtime.CompilerServices
 2 // using System.Diagnostics;
 3 
 4 public void DoProcessing()
 5 {
 6     TraceMessage("Something happened.");
 7 }
 8 
 9 public void TraceMessage(string message,
10         [CallerMemberName] string memberName = "",
11         [CallerFilePath] string sourceFilePath = "",
12         [CallerLineNumber] int sourceLineNumber = 0)
13 {
14     Trace.WriteLine("message: " + message);
15     Trace.WriteLine("member name: " + memberName);
16     Trace.WriteLine("source file path: " + sourceFilePath);
17     Trace.WriteLine("source line number: " + sourceLineNumber);
18 }
19 
20 // Sample Output:
21 //  message: Something happened.
22 //  member name: DoProcessing
23 //  source file path: c:\Users\username\Documents\Visual Studio 2012\Projects\CallerInfoCS\CallerInfoCS\Form1.cs
24 //  source line number: 31
 
备注
 
不能将调用方信息特性应用于未指定为选项的参数。

相反,它们影响传递的默认值,当参数省略时。

StackTrace 属性的结果异常的,结果不影响的经过模糊处理的。

 

成员名称

此优势为以下任务特别有用:

  • 使用跟踪和诊断实例。

  • 不 CallerMemberName 属性,必须指定属性名称为文本。

以下图表显示返回的成员名称,当您使用 CallerMemberName 属性。

 

调用发生中

成员名称结果

方法、属性或事件

方法的名称,该属性,或者的事件调用为。

构造函数

字符串 “.ctor”

静态构造函数

字符串 “.cctor”

析构函数

该字符串 “Finalize”

用户定义的运算符或转换

生成的名称成员,例如, “op_Addition”。

特性构造函数

如果属性是在成员中的任何元素 (如参数、返回值或泛型类型参数),此结果是与组件关联的成员的名称。

不包含的成员

(例如,程序集级别或特性应用于型)

可选参数的默认值。

 

 

 

相关文章: