プロパティのカスタム属性を作成していますが、get アクセサー内の属性の値にアクセスする方法を誰かが知っているかどうか疑問に思っていました。
public class MyClass
{
[Guid("{2017ECDA-2B1B-45A9-A321-49EA70943F6D}")]
public string MyProperty
{
get { return "value loaded from guid"; }
}
}
プロパティのカスタム属性を作成していますが、get アクセサー内の属性の値にアクセスする方法を誰かが知っているかどうか疑問に思っていました。
public class MyClass
{
[Guid("{2017ECDA-2B1B-45A9-A321-49EA70943F6D}")]
public string MyProperty
{
get { return "value loaded from guid"; }
}
}
そんな知恵は置いといて…
public string MyProperty
{
get
{
return this.GetType().GetProperty("MyProperty").GetCustomAttributes(typeof(GuidAttribute), true).OfType<GuidAttribute>().First().Value;
}
}
次のように、リフレクションを介してプロパティとそのカスタム属性を取得できます。
// 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;