如何在.Net Framework中将方法注入到自动属性中
我有一些具有许多属性的 Foo 类:
public class Foo
{
public int Property1 { get; set; }
public int Property2 { get; set; }
public int Property3 { get; set; }
}
在其他类中我有一些方法,例如
public void SomeMethod()
{
//...
}
如何将此方法注入到 Foo 类中的每个属性设置器中? 我使用.Net Framework 2.0
I have some class Foo with many properties:
public class Foo
{
public int Property1 { get; set; }
public int Property2 { get; set; }
public int Property3 { get; set; }
}
In other class I have some method, e.g.
public void SomeMethod()
{
//...
}
How to inject this method to every setter of properties in the class Foo?
I use .Net Framework 2.0
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为没有办法在运行时通过反射来做到这一点。您可能想要做的是使用 AOP(面向方面)方法,但 .NET 框架也不真正支持这种方法。如果您不介意使用编译器扩展,则可以使用 PostSharp 来执行此操作,或者查看使用 Unity2 进行 AOP。
编辑:
您还可以考虑Castle DynamicProxy。
或者,如果您牢牢掌握 DynamicMethods 和 IL 代码,您可以创建自己的代理生成器类。
但是,我认为在大多数情况下,您必须对应用程序的其余部分进行适当的编码才能处理代理。换句话说,
您不必执行以下操作,而必须执行以下操作:
I don't think there is a way to do that at runtime with reflection. What you would probably want to do is use an AOP (aspect-oriented) approach, but that too isn't really supported by the .NET framework. You could use PostSharp to do it, if you don't mind using a compiler extension, or look into using Unity2 to do AOP.
Edit:
You could also consider Castle DynamicProxy.
Or, if you have a firm grasp of DynamicMethods and IL code, you could make your own proxy generator class.
However, I think in most cases, you will have to code the rest of your application appropriately to handle the proxies. In other words, instead of doing:
You would have to do something like:
您可以在此处使用
int
类的扩展。或者无论您的 getter/setter 属性是什么数据类型。例如,
扩展方法将如下所示
,请参阅以下文章以将其与 .NET 2.0 一起使用。要求您使用支持 C# 3.0 的 VisualStudio,但它仍可与 C# 2.0 一样使用输出框架
C# 2.0 中的扩展方法
You can use an extension of the
int
class here. Or whatever data type your getter/setter properties are.For example
The extension method would look like this
See the following article to use it with .NET 2.0. Requires that you use a VisualStudio that supports C# 3.0 but it will still work with the output framework as C# 2.0
Extension Method in C# 2.0
我找到了简单的方法来做到这一点。我使用 EasyProp,它使用 Castle DynamicProxy:
我的类:
使用示例:
您还需要添加这样的方法:
I found easy way to do this. I use EasyProp, which uses Castle DynamicProxy:
My class:
Example of use:
Also you need to add such method: