简体   繁体   English

使用System.Reflection.Emit命名空间将字段替换为Property?

[英]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. 我试图找出一种使用Reflection.Emit命名空间删除字段并将其替换为我自己的Property实现的方法。 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; 我一直在阅读如何使用Emit生成代码以及直接编写和编译IL代码,但是我还没有看到任何有关如何使用Reflection.Emit命名空间进行替换或删除的示例。 Can anyone show me any examples of something along those lines? 有人可以向我展示任何类似的例子吗?

Thanks. 谢谢。

To my knowledge this is impossible in the CLR. 据我所知,这在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. 根据您计划使用该属性的方式,可以使用自定义TypeDescriptor(组件使用它来动态扩展属性,例如Windows窗体中的ToolTip组件),也可以使用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? 为什么不使用Assembly.ReflectionOnlyLoadFrom来加载DLL,然后再将程序集加载到AppDomain中,然后发出具有动态生成的类型的类型,然后再加载该类型?

You might try looking into Aspect Oriented Programming with Postsharp. 您可以尝试使用Postsharp研究面向方面的编程。

I have never used Postsharp, so I have no specific ideas on how exactly you might accomplish this. 我从来没有使用过Postsharp,因此对于您将如何完成此工作我没有明确的想法。 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). 但是,这听起来确实类似于我听说可以使用Postsharp(设置代码以运行属性或字段的事前/事后访问)的某些事情。

http://www.postsharp.org/ http://www.postsharp.org/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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