简体   繁体   中英

Replace Field with Property using System.Reflection.Emit namespace?

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.

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?

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM