从具有强类型的 属性 获取自定义属性
Get a custom attribute from a property with strong typing
我有一个 class Foo
和一个 属性 Bar
,它有一个我想检索的自定义属性。
public class Foo {
[ThisAttribute("The string I want to get")]
public string Bar { get; set; }
}
我可以这样获取属性值
var name = typeof(Foo).GetProperty("Bar").GetCustomAttribute(typeof(ThisAttribute)).PropertyName;
但是,如果 属性 被重命名,这将会中断。有没有一种方法可以在不对 属性 的字符串名称进行硬编码的情况下检索属性,而是直接引用特定的 属性?
最好的方法是使用 nameof
:
var name = typeof(Foo)
.GetProperty(nameof(Foo.Bar))
.GetCustomAttribute<ThisAttribute>()
.PropertyName;
然后如果你重命名Bar
那么它会导致编译错误。
显然它不会强制使用 属性 of Foo
,因此仍然可能导致运行时异常,但由于上述原因,它比使用字符串更安全。
请注意 GetCustomAttribute
也有泛型重载。
我有一个 class Foo
和一个 属性 Bar
,它有一个我想检索的自定义属性。
public class Foo {
[ThisAttribute("The string I want to get")]
public string Bar { get; set; }
}
我可以这样获取属性值
var name = typeof(Foo).GetProperty("Bar").GetCustomAttribute(typeof(ThisAttribute)).PropertyName;
但是,如果 属性 被重命名,这将会中断。有没有一种方法可以在不对 属性 的字符串名称进行硬编码的情况下检索属性,而是直接引用特定的 属性?
最好的方法是使用 nameof
:
var name = typeof(Foo)
.GetProperty(nameof(Foo.Bar))
.GetCustomAttribute<ThisAttribute>()
.PropertyName;
然后如果你重命名Bar
那么它会导致编译错误。
显然它不会强制使用 属性 of Foo
,因此仍然可能导致运行时异常,但由于上述原因,它比使用字符串更安全。
请注意 GetCustomAttribute
也有泛型重载。