Determine field from attribute

  • Thread starter Thread starter Mihajlo Cvetanović
  • Start date Start date
M

Mihajlo Cvetanović

With Attribute.GetCustomAttribute() I can obtain the attribute if I have
the field. How can I achieve the opposite, how can I obtain the field
from within the attribute? I want to check the field type in MyAttribute
constructor, and throw exception if attribute and filed mismatch.
Something like more detailed AttributeUsage functionality.
 
Hi Mihajlo Cvetanovic,

You wrote on 19/02/2010 :
With Attribute.GetCustomAttribute() I can obtain the attribute if I have the
field. How can I achieve the opposite, how can I obtain the field from within
the attribute? I want to check the field type in MyAttribute constructor, and
throw exception if attribute and filed mismatch. Something like more detailed
AttributeUsage functionality.

I think there is no way to reverse the situation, maybe the only way is
to analyze the stack trace to try to understand who is calling the
attribute ctor.

..m

--
Mauro Servienti
{C67C0157-5D98-4733-A75E-93CAEE4BADC8}
Microsoft MVP - Visual C# / MCP
http://mvp.support.microsoft.com
http://blogs.ugidotnet.org/topics
whynot [ at ] topics [ dot ] it
 
Mihajlo said:
With Attribute.GetCustomAttribute() I can obtain the attribute if I have
the field. How can I achieve the opposite, how can I obtain the field
from within the attribute? I want to check the field type in MyAttribute
constructor, and throw exception if attribute and filed mismatch.
Something like more detailed AttributeUsage functionality.

You can't. Not in the constructor at least.

To achieve what you want, you could start your own hierarchy of
attributes, which as an virtual Accept(MemberInfo) method or something
similar.

After retrieving the attributes from a MemberInfo, call the Accept()
method on all attributes, passing the member to it.

By overriding and implementing the Accept() method in concrete
descendants of the base attribute, they can then decide whether they
were actually allowed to be placed on that MemberInfo to begin with.
 
Willem said:
By overriding and implementing the Accept() method in concrete
descendants of the base attribute, they can then decide whether they
were actually allowed to be placed on that MemberInfo to begin with.

Thanks for quick reply. I have something similar already in place,
checking whether an Object parameter is of required type.

I just wanted to check it on startup (perfect would be in compile time),
rather than in run time.
 
I just wanted to check it on startup (perfect would be in compile time),
rather than in run time.

create a console application that performs the checks in a post build
event
 
Back
Top