问题
I'm working on a silly game where the player controls their character by programming procedures for it to follow. I'm using C# codeDOM to compile the code the player writes and I'd like for the player to be able to call functions written into the pre-compiled part of the software. For example:
Player-written code to be compiled at run-time by codeDOM:
namespace AutoCrawl
{
public class Player
{
public void Go_Up()
{
Move("Up");
}
}
}
My pre-compiled code:
private void compileUserCode()
{
string code = UserCodeTextBox.Text;
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerParameters parameters = new CompilerParameters();
parameters.GenerateInMemory = true;
parameters.GenerateExecutable = false;
CompilerResults results = provider.CompileAssemblyFromSource(parameters, code);
}
private void Move(string direction)
{
//move the player's character in the direction specified by "direction"
}
The problem is that I don't know how to tell the codeDOM compiler that it can find the function 'Move'
in my own, pre-compiled code. I get the following error from the codeDOM compiler:
Error (CS0103): The name 'Move' does not exist in the current context
Is it even possible? I can't seem to find any examples of other people using codeDOM in this way.
Thank you for your help!
回答1:
Best way to do this is set the ReferencedAssemblies property on your CompilerParameters to be a lib that contains your additional code.
var parameters = CompilerParameters
{
ReferencedAssemblies = {
"my.dll",
// etc
}
};
Here is a longer blog post on the subject including link to github http://danielslaterblog.blogspot.co.uk/2015/05/programming-programming-computer-game.html
来源:https://stackoverflow.com/questions/30299902/possible-to-use-c-sharp-codedom-to-call-back-to-pre-compiled-functions