I can use TypeDescriptor.AddAttributes to add an attribute to a type in runtime. How do I do the same for a method and parameter? (maybe 2 separate questions...)
-
In what situations do you want the attributes to appear?SLaks– SLaks2010-03-07 19:07:50 +00:00Commented Mar 7, 2010 at 19:07
-
For reflection, hence I noticed even TypeDescriptor.AddAttribute doesnt work for that.MatteS– MatteS2010-03-08 14:38:32 +00:00Commented Mar 8, 2010 at 14:38
2 Answers
TypeDescriptor.AddAttributes only affects a very specific use-case; i.e. from within System.ComponentModel. For the rest of reflection, it knows nothing about the extra attribute. And indeed, System.ComponentModel doesn't really apply to methods or parameters.
So in short; you can't. You will need to store this information somewhere else (bespoke), or add it at compile-time.
5 Comments
TypeDescriptor and TypeDescriptionProvider aren't implemented?User class that implements IUser on the server. The generated client-entity implement IIdentity.IsAuthenticated, and I wanted to attribute it with [Display(AutoGenerateField=false)]. I tried to make a matching dummy property on server and mark it with Exclude so it's not generated twice, then add metadata for it in the metadata body class, the metadata should be generated for the existing property on the client as well, but that didn't work. Generated IsAuthenticated remains unattributed on clientAs I see from analyzing the TypeDescriptor class in Reflector, the .AddAttributes method internally calls the .AddProvider method. The TypeDescriptionProvider instance passed to it is actually responsible for providing meta-data. You could try adding the [TypeDescriptionProviderAttribute] attribute to your class and implement your own provider by deriving from the TypeDescriptionProvider class. As the documentation says, by overriding TypeDescriptionProvider.CreateInstance, you could provide a substitute object whose type has all necessary attributes. I suspect that the attributes applied to methods inside the substitution type will also take effect. However, I haven't tried that myself, so feel free to experiment...