问题
Possible Duplicate:
Execute a string in C# 4.0
How can I get this string to execute:
string dt = "DateTime.Now";
...so that this would result in today's date being displayed?:
lbl.Text = dt;
回答1:
Solution with Codedom:
private static string CreateExecuteMethodTemplate(string content)
{
var builder = new StringBuilder();
builder.Append("using System;");
builder.Append("\r\nnamespace Lab");
builder.Append("\r\n{");
builder.Append("\r\npublic sealed class Cal");
builder.Append("\r\n{");
builder.Append("\r\npublic static object Execute()");
builder.Append("\r\n{");
builder.AppendFormat("\r\nreturn {0};", content);
builder.Append("\r\n}");
builder.Append("\r\n}");
builder.Append("\r\n}");
return builder.ToString();
}
private static object Execute(string content)
{
var codeProvider = new CSharpCodeProvider();
var compilerParameters = new CompilerParameters
{
GenerateExecutable = false,
GenerateInMemory = true
};
compilerParameters.ReferencedAssemblies.Add("system.dll");
string sourceCode = CreateExecuteMethodTemplate(content);
CompilerResults compilerResults = codeProvider.CompileAssemblyFromSource(compilerParameters, sourceCode);
Assembly assembly = compilerResults.CompiledAssembly;
Type type = assembly.GetType("Lab.Cal");
MethodInfo methodInfo = type.GetMethod("Execute");
return methodInfo.Invoke(null, null);
}
So you can call:
var result = Execute("DateTime.Now");
来源:https://stackoverflow.com/questions/14485226/convert-string-to-executable-c-sharp-code-in-code-behind