如何获取引用字段的属性
我有一个问题: 是否有一种优雅的方式来获取引用字段的属性。 即:
public class C1: Base
{
[MyAttribute]
public string Field1;
}
public class Base
{
private void Do(ref string field)
{
if (field has attributes)
DoSomething();
}
}
如何在 Do() 方法中获取字段的属性?
提前致谢。
I have a question:
Is there an elegant way of getting Attributes on a referenced field.
Ie.:
public class C1: Base
{
[MyAttribute]
public string Field1;
}
public class Base
{
private void Do(ref string field)
{
if (field has attributes)
DoSomething();
}
}
How can I get attributes of a field in the method Do()?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您无法使用
ref string field
签名来做到这一点。属性应用于声明(字段、类、事件等),而不是“实例”。您可以做的是像这样改变您的方法:
然后使用反射来检查
fieldContainingType
以查看哪些属性应用于名为fieldName
的字段>。然而,这种方法极其脆弱并且通常非常糟糕。There's no way you can do that with
ref string field
signature. Attributes are applied to declarations (fields, classes, events etc.), not to "instances".What you can do, is alter your method like this:
and then use reflection to inspect
fieldContainingType
to see, what attributes are applied to field namedfieldName
. This approach, however, is extremely fragile and generally very bad.