1

プロパティのカスタム属性を作成していますが、get アクセサー内の属性の値にアクセスする方法を誰かが知っているかどうか疑問に思っていました。

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 に答える