程式中有需要將那些屬性名稱當作參數傳給某個Method嗎? 可利用CallerMemberNameAttribute來避免寫死屬性名稱哦!
環境:.NET 4.5
MSDN上的說明 CallerMemberNameAttribute 類別 : 可讓您取得方法呼叫端的方法或屬性名稱
那要如何取得「呼叫端資訊」呢?
只要在Method中設定CallerMemberNameAttribute(要using System.Runtime.CompilerServices;),就可以在Method中取得呼叫端資訊,如下為MSDN的範例,
//using System.Runtime.CompilerServices;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
TraceMessage("Hi, Rainmaker!");
}
public 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);
}
}
}
那CallerMemberNameAttribute 類別適合用在那裡呢?
如果程式中有需要將那些屬性名稱當作參數傳給某個Method的話,就得適合用這個,您就不需要在程式中寫死屬性名稱,如實作 INotifyPropertyChanged 的Class,原本在屬性改變時,要呼叫OnPropertyChanged("屬性名稱");。
有了CallerMemberNameAttribute 類別就可以不用在程式中寫死屬性名稱了,OnPropertyChanged();,如下,
public string SomeProperty
{
get
{
return _someProperty;
}
set
{
if (value != _someProperty)
{
_someProperty = value;
//You dont need to pass string of the propertyname, compiler will do for us.
//OnPropertyChanged("SomeProperty"); - no need any more
OnPropertyChanged();
}
}
}
/// <summary>
/// Notifies when the property is changed
/// </summary>
/// <param name="propertyName">New Features in C# 5, that you can easely skip writing string of property name.</param>
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
//whatever you need to be called
}
詳細請參考「New feature in C# 5.0 – [CallerMemberName]」。
參考資料
New feature in C# 5.0 – [CallerMemberName]
Hi,
亂馬客Blog已移到了 「亂馬客 : Re:從零開始的軟體開發生活」
請大家繼續支持 ^_^