如何在运行时替换方法实现? [英] How do I replace a method implementation at runtime?

查看:31
本文介绍了如何在运行时替换方法实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要属性 getter 和方法,我可以用我自己的自定义属性装饰它们,并根据该属性的存在用不同的实现替换方法主体.此外,不同的实现将需要知道赋予自定义属性的构造函数参数,用于装饰方法.

I'd like to have property getters and methods that I can decorate with my own custom attribute and based on the presence of that attribute replace the method bodies with a different implementation. Also, that different implementation will need to know the constructor arguments given to the custom attribute where it decorates the method.

这显然可以用 AOP 来完成,比如 PostSharp 或 LinFu,但我想知道是否有一种方法可以做到这一点,而不涉及构建后处理步骤,因为添加这比我更喜欢的项目复杂化.

This can obviously be done with AOP, like PostSharp or LinFu, but I'm wondering if there's a way to do this that does not involve a post-build processing step because adding that complicates the project more than I would prefer.

推荐答案

使用传统的 .Net API 无法实现这一点.方法体在编译时是固定的,不能更改.

Using the traditional .Net APIs there is no way to achieve this. Method bodies are fixed at compile time and cannot be changed.

我之所以说传统,是因为使用分析器和 ENC API,在技术上可以更改方法主体.但这些 API 在受限环境中运行,不被视为通用 API.

I say traditional though because with the profiler and ENC APIs it's technically possible to change method bodies. But these APIs operate in constrained circumstances and are not considered to be general purpose APIs.

这篇关于如何在运行时替换方法实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆