繁体   English   中英

获取要在自定义属性中使用的属性值

[英]Get property value to use within custom attribute

我一直在寻找一个示例,该示例如何从自定义属性的代码中获取属性的值。

仅用于说明目的的示例:我们有一个只有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);
    }
}

我希望这对您的工作有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM