Where would you use C# Runtime Compilation?

前端 未结 7 1353
余生分开走
余生分开走 2021-02-20 05:34

I happened upon a brief discussion recently on another site about C# runtime compilation recently while searching for something else and thought the idea was interesting. Have

7条回答
  •  南旧
    南旧 (楼主)
    2021-02-20 06:19

    Well, all C# code is run-time compiled, since it's a JIT (just-in-time) compiler. I assume you are referring to Reflection.Emit to create classes etc. on the fly. Here's an example I have seen recently in the Xml-Rpc.Net library.

    I create a C# interface that has the same signature as an XML-RPC service's method calls, e.g.

    IMyProxy : IXmlRpcProxy
    {
        [XmlRpcMethod]
        int Add(int a, int b);
    }
    

    Then in my code I call something like

    IMyProxy proxy = (IMyProxy)XmlRcpFactory.Create(typeof(IMyProxy));
    

    This uses run-time code generation to create a fully functional proxy for me, so I can use it like this:

    int result = proxy.Add(1, 2);
    

    This then handles the XML-RPC call for me. Pretty cool.

提交回复
热议问题