标题中所说的三个特性 CallerMemberNameAttribute / CallerFilePathAttribute / CallerLineNumberAttribute 我们统称为调用者信息特性,正常情况下在 .NET Framework 4.0 中是无法使用的。
static void Main( string[] args )
{
var productInfo = new ProductInfo(); productInfo.Name = "lumia"; productInfo.PropertyChanged(); Console.ReadKey( true );
}
} public class ProductInfo
{
private string _name; public string Name
{
get { return this._name; }
set
{
this._name = value;
this.PropertyChanged();
}
} public void PropertyChanged([CallerMemberName]string name = "", [CallerLineNumber]int line = , [CallerFilePath]string file = "")
{
Console.WriteLine("------------------------------------------------");
Console.WriteLine($"Name : {name}, \nLine : {line}, \nPath : {file}");
}
}
在 .NET Framework 4.0 中使用需要自己定义这三个特性
namespace System.Runtime.CompilerServices
{
[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
public class CallerMemberNameAttribute : Attribute
{ } [AttributeUsage(AttributeTargets.Parameter, Inherited = false )]
public class CallerFilePathAttribute : Attribute
{ } [AttributeUsage(AttributeTargets.Parameter, Inherited = false )]
public class CallerLineNumberAttribute : Attribute
{ }
}