我一直在寻找一个示例,该示例如何从自定义属性的代码中获取属性的值。
仅用于说明目的的示例:我们有一个只有name属性的简单book类。name属性具有一个自定义属性:
public class Book
{
[CustomAttribute1]
property Name { get; set; }
}
在自定义属性的代码中,我想获取装饰属性的属性的值:
public class CustomAttribute1: Attribute
{
public CustomAttribute1()
{
//I would like to be able to get the book's name value here to print to the console:
// Thoughts?
Console.WriteLine(this.Value)
}
}
当然,“ this.Value”不起作用。有什么想法吗?
好,我知道了。但是,仅适用于.Net 4.5和更高版本。
在System.Runtime.CompilerServices库中,有一个CallerMemberNameAttribute类可用。要获取调用类的名称,有一个CallerFilePathAttribute类,该类返回调用类的完整路径,以供以后与Reflection使用。两者的用法如下:
public class CustomAttribute1: Attribute
{
public CustomAttribute1([CallerMemberName] string propertyName = null, [CallerFilePath] string filePath = null)
{
//Returns "Name"
Console.WriteLine(propertyName);
//Returns full path of the calling class
Console.WriteLine(filePath);
}
}
我希望您觉得这对您的工作有帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句