Question

I am reflecting on assemblies and collecting custom attributes on types and members. However I need to read those attribute declarations "as they appear in the code" (or compiled assembly when you browse the assembly in object browser).

So if the assembly has a type declaration like:

[Serializable]
[Author("John Doe", version=1.1)]
class C {}

when I reflect on type C and get its attributed using typeof(C).GetCustomAttributes() , it just gives me object[] containing "instances" of those attribute types. But I need them, just like they appear in the code: <ConstructorRef, Arguments>

<Serializable(), []>
<Author(string,int), ["John Doe", 1.1]>

Is there a way to go back from "attribute instance" to "attribute declaration"? Because there could be many constructors of an attribute type and attribute might not expose any properties at all that you can match with the constructor. That doesn't seem like an option.

Bonus question: How object/assembly browsers in IDEs (e.g. VS) can see constant arguments passed to the attribute constructors? Is it via disassembly or reflection? If it's only possible with disassembly, I guess I am out of luck here.

I need this to reflect on assemblies and generate code from them. So I need to mimic custom attributes on types and members, but so far I am clueless. Any help is appreciated.

Was it helpful?

Solution

Yes, take a look at CustomAttributeData. BTW it's the only way to access custom attributes if you load an assembly for reflection only (it doesn't instantiate the attributes). I'm pretty sure that reflection APIs can decode every information from an assembly apart from IL code, which is only exposed as a byte array. But if you hit a wall, there is Mono Cecil for example.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top