3

For example, would it be possible to mark a 'Man' class with the 'PetOwner' attribute, which overrides the constructor with something that creates a 'Dog' object as well as calling the 'Man' base constructor?

(And overrides 'Man's 'GoForWalk()' method to include interaction with his Dog?)

I'm quite new to Reflection, and was curious about this so I figured I may as well ask. Does this involve Reflection.Emit somehow?

I also had a look at this question, but I dont think it fully relates to what I am asking (and I dont fully understand it either).

Thanks for any help! :)

EDIT: This question looks similar to what I'm going for

Community
  • 1
  • 1
Aralox
  • 1,441
  • 1
  • 24
  • 44
  • 1
    What do you really want to do? It seems to be an [XY Problem](http://www.perlmonks.org/?node_id=542341) – L.B Mar 11 '12 at 01:29
  • I was considering using this to create a way of mirroring the visual parts of winforms controls in Mogre, but I found another way that works nicely. Now (as I mentioned), I am just curious about whether this is possible – Aralox Mar 11 '12 at 01:43
  • Why do you want to use custom attributes instead of implementing a proper object model? I'm not saying the attribute couldn't aide in the object model, but working with IL rewriters is heavy and ugly. – M.Babcock Mar 11 '12 at 01:53
  • Again, I am not asking for a solution for a particular problem, I am just asking if this is possible. This is not an XY problem - if an example would help, I have already provided one (the 'Man' and 'Dog' classes) – Aralox Mar 11 '12 at 02:36

1 Answers1

2

Yes and no, it depends on different aspects of what you actualy want to achieve, so a bit more information would probably be helpful. Since you ask about reflection, I get the impression that you have existing libraries that you want to extend with your own functionality, but it is not clear from your explanation.

The .net Framework and C# allow for different ways of overriding code / changing behaviour, but everything depends on when the information for overriding is available; at design time (-> typical OO construct), after the compilation step (-> aspect oriented programming) or at compile time (-> reflection / dynamic features).

Most of the time, reflection is the last resort, because it inherently has a performance hit to deal with (certainly if in addition to using reflection to read the attributes, you also need to create additional code and execute it). That being said, Reflection.Emit is indeed a way of overriding accessible methods (by emitting a method with the same name and signature).

Dirk
  • 2,348
  • 17
  • 23
  • Thanks Dirk :) you have also led me on to another interesting topic I want to read about - aspect oriented programming – Aralox Mar 11 '12 at 10:01