C#动态编译并执行字符串样例
本文实例为大家分享了Android九宫格图片展示的具体代码,供大家参考,具体内容如下
usingSystem;
usingMicrosoft.CSharp;
usingSystem.CodeDom.Compiler;
classProgram
{
publicstaticvoidMain()
{
//TheC#codetoexecute
stringcode="usingSystem;"+
"usingSystem.IO;"+
"publicclassMyClass{"+
"publicstaticvoidPrintConsole(stringmessage){"+
"Console.WriteLine(message);"+
"}"+
"}";
//CompilerandCompilerParameters
CSharpCodeProvidercodeProvider=newCSharpCodeProvider();
CompilerParameterscompParameters=newCompilerParameters();
//Compilethecode
CompilerResultsres=codeProvider.CompileAssemblyFromSource(compParameters,code);
//Createanewinstanceoftheclass'MyClass'//有命名空间的,需要命名空间.类名
objectmyClass=res.CompiledAssembly.CreateInstance("MyClass");
//Callthemethod'PrintConsole'withtheparameter'HelloWorld'
//"HelloWorld"willbewritteninconsole
myClass.GetType().GetMethod("PrintConsole").Invoke(myClass,newobject[]{"HelloWorld"});
Console.Read();
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。