3

可能重复:
在 C# 4.0 中执行字符串

我怎样才能让这个字符串执行:

string dt = "DateTime.Now";

...这样会导致显示今天的日期?:

lbl.Text = dt;
4

1 回答 1

7

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);
}

所以你可以打电话:

var result = Execute("DateTime.Now");
于 2013-01-23T17:30:05.373 回答