【发布时间】: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