【问题标题】:Get property value to use within custom attribute获取要在自定义属性中使用的属性值
【发布时间】:2015-04-26 22:55:22
【问题描述】:

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

示例仅用于说明目的:我们有一个只有 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”不起作用。有什么想法吗?

【问题讨论】:

  • 这取决于您的用例,有时使用 CustomAttribute[name="something"] 会更容易。但我认为如果你愿意,你应该使用反射,你想要什么。看看stackoverflow.com/questions/6637679/…
  • 实际上,这与我正在寻找的相反(上面的链接允许查找已提供属性的属性,并且您可以获得名称和值)。我正在寻找的是,一旦调用了 CustomAttribute 代码,CustomAttribute 代码就知道它是从 name 属性调用的,并且可以检测到属性的值。如果我可以从 CustomAttribute 中检测到类名和属性名,我可以使用反射来获取值,但我似乎做不到。
  • 你想达到什么目标,为什么你认为属性是正确的方法?

标签: c# reflection attributes custom-attributes


【解决方案1】:

好的,我想通了。不过,这仅适用于 .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);
    }
}

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

【讨论】:

  • 谢谢!这对汤姆很有帮助!
猜你喜欢
  • 2011-03-18
  • 1970-01-01
  • 2013-05-30
  • 2015-04-18
  • 1970-01-01
  • 1970-01-01
  • 2019-05-20
  • 2015-07-27
相关资源
最近更新 更多