views:

545

answers:

2

I'm trying to figure out a way to use the Reflection.Emit namespace to remove a field and replace it with my own Property implementation. I've been reading on how to generate code using Emit and writing and compiling IL code directly, but I haven't seen any examples on how to do a replace or remove using the Reflection.Emit namespace; Can anyone show me any examples of something along those lines?

Thanks.

+1  A: 

To my knowledge this is impossible in the CLR. I don't even think you could amend a type once it has been loaded. Depending on how you plan to use the property, you could possibly use either a custom TypeDescriptor (components use this to dynamically extend properties such as the ToolTip component in Windows Forms) or you may be able to use DependencyProperty. But as for plain old late binding to a new or modified member of a loaded type, I don't think that's possible.

Why not use the Assembly.ReflectionOnlyLoadFrom to load the DLL prior to loading the assembly into the AppDomain then emit a new type with the dynamically generated type in memory and then load that?

Josh Einstein
I'm working on a property grid type control that can also modify fields, hashtables, etc. But, I don't currently have any way of being notified when a field, or basically anything is modified outside of my control expect for properties. So when the user sets the selected object on my control I want to go in and replace a fields with a property and define some logic for notifications... Its a long shot, but there's go to be someway to do this...
Thrash505
IPropertyChanged is one concept.http://www.msnewsgroups.net/group/microsoft.public.dotnet.languages.csharp/topic36704.aspx
eschneider
Is it possible to take the selected object, create a new type based off it in memory, implement my custom logic, then break any old associations with the old type, and then re-link them with the new type? I was looking through the TypeDescriptors members and I seen a bunch of Association methods... thought they might be of use.
Thrash505
I think you are correct. After searching for several days, I don't see anyway to do this. Existing code can't be removed at run-time, you can only create new types, etc. Thanks.
Thrash505
+1  A: 

You might try looking into Aspect Oriented Programming with Postsharp.

I have never used Postsharp, so I have no specific ideas on how exactly you might accomplish this. However, this does sound strikingly similar to some things that I've heard you can do with Postsharp (set up code to run pre/post access of a property or field).

http://www.postsharp.org/

If you do look into PostSharp, look into its weaver. The LAOS (Lightweight Aspect Oriented System) allows you to add behavior to existing methods, properties, etc. However you will likely need to use low-level weaving to replace a field with a property.
jrista