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.
精彩评论