Convert string to executable c# code in code-behind [duplicate]

瘦欲@ 提交于 2021-02-18 17:15:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!