开发者

How to get attributes on a referenced field

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.


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:

private void Do(Type fieldContainingType, string fieldName, ref string field)

and then use reflection to inspect fieldContainingType to see, what attributes are applied to field named fieldName. This approach, however, is extremely fragile and generally very bad.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜