C# monkey patching - is it possible?

巧了我就是萌 提交于 2019-12-10 19:23:52

问题


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;
        }
    }
}

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


回答1:


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.




回答2:


It is possible to access extension methods from IronPython. See http://blogs.msdn.com/saveenr/archive/2008/11/14/consuming-extension-methods-in-ironpython.aspx




回答3:


you can use reflection to get this method into another assembly

i dont know about IronPython but i think this will help you

http://www.voidspace.org.uk/ironpython/dynamically_compiling.shtml




回答4:


I don't believe that it's possible to extend an existing .NET type once it's created.

If all you need is a byte[] (in IronPython, I presume), you can do:

>>> import clr
>>> import System
>>> b = bytes([1, 2, 3, 4])
>>> a = System.Array[bytes](b)
>>> a
Array[bytes]((b'\x01', b'\x02', b'\x03', b'\x04'))

However, it's unlikely that IronPython will ever allow access to Bytes' underlying storage (unless CPython does), as it's not safe.



来源:https://stackoverflow.com/questions/2853672/c-sharp-monkey-patching-is-it-possible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!