1

我正在为我的属性创建一个自定义属性,并且想知道是否有人知道我如何访问 get 访问器内部的 Attribute 的值。

public class MyClass
{
    [Guid("{2017ECDA-2B1B-45A9-A321-49EA70943F6D}")]
    public string MyProperty
    {
        get { return "value loaded from guid"; }
    }
}
4

2 回答 2

1

抛开这种事情的智慧......

public string MyProperty
{
    get
    {
        return this.GetType().GetProperty("MyProperty").GetCustomAttributes(typeof(GuidAttribute), true).OfType<GuidAttribute>().First().Value;
    }
}
于 2010-08-20T00:17:42.927 回答
0

您可以通过反射检索属性,然后检索其自定义属性,如下所示:

// Get the property
var property = typeof(MyClass).GetProperty("MyProperty");

// Get the attributes of type “GuidAttribute”
var attributes = property.GetCustomAttributes(typeof(GuidAttribute), true);

// If there is an attribute of that type, return its value
if (attributes.Length > 0)
    return ((GuidAttribute) attributes[0]).Value;

// Otherwise, we’re out of luck!
return null;
于 2010-08-20T00:19:46.907 回答