C#的变迁史09 - C# 5.0 之调用信息增强篇
Caller Information
CallerInformation是一個簡單的新特性,包括三個新引入的Attribute,使用它們可以用來獲取方法調用者的信息,
這三個Attribute在System.Runtime.CompilerServices命名空間下,分別叫做CallerMemberNameAttribute,CallerFilePathAttribute和CallerLineNumberAttribute。
CallerMemberNameAttribute:用來獲取方法調用者的名稱 CallerFilePathAttribute:用來獲取方法調用者的源代碼文件路徑 CallerLineNumberAttribute:用來獲取方法調用者所在的行號簡單看一個小例子:
using System; using System.Runtime.CompilerServices;class Program {static void Main(string[] args){DoProcessing();Console.ReadKey();}static void DoProcessing(){TraceMessage("Something happened.");}static void TraceMessage(string message,[CallerMemberName] string memberName = "",[CallerFilePath] string sourceFilePath = "",[CallerLineNumber] int sourceLineNumber = 0){Console.WriteLine("message: " + message);Console.WriteLine("member name: " + memberName);Console.WriteLine("source file path: " + sourceFilePath);Console.WriteLine("source line number: " + sourceLineNumber);} }不用多說了,結果很清楚。
不過需要注意,Caller Info的這些Attribute只能用在optional parameter上,也就是說要指定默認值的。
此外對于CallerMemberNameAttribute需要多說一點,使用這個Attribute可以避免在程序中硬編碼調用方的函數名,至于這個屬性返回的名字一般是這樣的:
| 調用方法的類型 | 獲取的結果 |
| 方法,屬性,事件 | 方法,屬性或事件的名字 |
| 構造函數 | 字符串".ctor" |
| 靜態構造函數 | 字符串".cctor" |
| Finalize函數 | 字符串"Finalize" |
| 用戶自定義的操作 | 編譯產生的名字,比如"op_Addition" |
| Attribute構造函數 | 應用此Attribute的成員函數名字。如果不是應用于成員的Attribute,比如說是應用于類型的Attribute,則使用其設置的默認值 |
?
這個特性在WPF的MVVM模式中很有用。在WPF的MVVM設計模式中的viewmodel里,我們是用INotifyPropertyChanged接口去通知在viewmodel里的改變。具體實現中很多的Binding是通過字符串來標識的,當修改一個Property的名字的時候,有時候很可能會忘記更新通知中的字符串名字,使用這個新的CallerMemberNameAttribute就能避免這個問題。
例如以前通常的一種實現是這樣的:
這種實現中Property的名字"Name"是以字符串的形式來約定的,一旦這個Property被Rename后忘記改了此處,就會帶來bug。使用新的Attribute以后就可以這么寫了:
public class EmployeeVM:INotifyPropertyChanged {public event PropertyChangedEventHandler PropertyChanged;public void OnPropertyChanged([CallerMemberName] string propertyName=null){if (PropertyChanged != null){PropertyChanged(this, new PropertyChangedEventArgs(propertyName));}}private string _name;public string Name{get { return _name; }set{_name = value;OnPropertyChanged();}} }這么一來就不用硬編碼了,簡單。
?
總結
以上是生活随笔為你收集整理的C#的变迁史09 - C# 5.0 之调用信息增强篇的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 基于diff的文件同步算法(上)
- 下一篇: 团办信用卡审核要多久