[.NET]CallerMemberNameAttribute
------------恢复内容开始------------
------------恢复内容结束------------
程序中有需要将那些属性名称当作参数传给某个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();
}
}
}
///
/// Notifies when the property is changed
///
///New Features in C# 5, that you can easely skip writing string of property name.
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
//whatever you need to be called
}
详细请参考“New feature in C# 5.0 – [CallerMemberName]”。
参考数据
CallerMemberNameAttribute 类
New feature in C# 5.0 – [CallerMemberName]
C# Tips and Traps
作者:大专栏
出处:https://www.dazhuanlan.com/2019/09/08/b946d31f058a/
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。