C#猴子修补-有可能吗? [英] C# monkey patching - is it possible?

查看:94
本文介绍了C#猴子修补-有可能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以编写一个C#程序集,该程序集在加载时会将方法从另一个程序集注入到类中?如果是,是否可以从使用ILR的语言(如IronPython)中使用注入的方法?

Is it possible to write a C# assembly which when loaded will inject a method into a class from another assembly? If yes, will the injected method be available from languages using DLR, like IronPython?

namespace IronPython.Runtime
{
    public class Bytes : IList<byte>, ICodeFormattable, IExpressionSerializable
    {
        internal byte[] _bytes;

        //I WANT TO INJECT THIS METHOD
        public byte[] getbytes()
        {
            return _bytes;
        }
    }
}

我需要该方法,并且如果可能的话,我希望避免重新编译IronPython.

I need that method, and I would like to avoid recompiling IronPython if possible.

推荐答案

这可以通过诸如 TypeMock ,该钩子连接到框架概要分析API.

This can be done with frameworks such as TypeMock, which hook into the framework profiling APIs.

但是,这种注入通常仅用于促进单元测试,而不是在生产代码中使用,并且会带来性能上的损失.我的观点是,如果您必须在单元测试之外做一些如此剧烈的事情,那么您可能做错了什么.

However this kind of injection is usually only used to facilitate unit testing rather than within production code and comes with a performance hit. My opinion is that if you are having to do something as drastic as this outside of unit testing, then do you are probably doing something wrong.

这篇关于C#猴子修补-有可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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