How can I wrote C# code to compile and run dynamically generated C# code. Are there examples around?
What I am after is to dynamically build up a C# class (or classes) and run them at runtime. I want the generated class to interact with other C# classes that are not dynamic.
I have seen examples that generate exe or dll files. I am not after that, I just want it to compile some C# code in memory and then run it. For instance,
So here is a class which is not dynamic, it will be defined in my C# assembly and will only change at compile time,
public class NotDynamicClass
{
private readonly List<string> values = new List<string>();
public void AddValue(string value)
{
values.Add(value);
}
public void ProcessValues()
{
// do some other stuff with values
}
}
Here is my class that is dynamic. My C# code will generate this class and run it,
public class DynamicClass
{
public static void Main()
{
NotDynamicClass class = new NotDynamicClass();
class.AddValue("One");
class.AddValue("two");
}
}
So the result is that at the end my non dynamic code would call ProcessValues and it would do some other stuff. The point of the dynamic code is to allow us or the client to add custom logic to the software.
Thanks.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…