Is it possible to dynamically compile and execute C# code fragments?

后端 未结 6 1737
伪装坚强ぢ
伪装坚强ぢ 2020-11-21 07:10

I was wondering if it is possible to save C# code fragments to a text file (or any input stream), and then execute those dynamically? Assuming what is provided to me would c

6条回答
  •  悲哀的现实
    2020-11-21 07:43

    Others have already given good answers on how to generate code at runtime so I thought I would address your second paragraph. I have some experience with this and just want to share a lesson I learned from that experience.

    At the very least, I could define an interface that they would be required to implement, then they would provide a code 'section' that implemented that interface.

    You may have a problem if you use an interface as a base type. If you add a single new method to the interface in the future all existing client-supplied classes that implement the interface now become abstract, meaning you won't be able to compile or instantiate the client-supplied class at runtime.

    I had this issue when it came time to add a new method after about 1 year of shipping the old interface and after distributing a large amount of "legacy" data that needed to be supported. I ended up making a new interface that inherited from the old one but this approach made it harder to load and instantiate the client-supplied classes because I had to check which interface was available.

    One solution I thought of at the time was to instead use an actual class as a base type such as the one below. The class itself can be marked abstract but all methods should be empty virtual methods (not abstract methods). Clients can then override the methods they want and I can add new methods to the base class without invalidating existing client-supplied code.

    public abstract class BaseClass
    {
        public virtual void Foo1() { }
        public virtual bool Foo2() { return false; }
        ...
    }
    

    Regardless of whether this problem applies you should consider how to version the interface between your code base and the client-supplied code.

提交回复
热议问题