在代码隐藏中将字符串转换为可执行的 C# 代码
本文关键字:代码 可执行 转换 字符串 隐藏 | 更新日期: 2023-09-27 17:55:20
可能的重复项:
在 C# 4.0 中执行字符串
如何让这个字符串执行:
string dt = "DateTime.Now";
。这样才能显示今天的日期?
lbl.Text = dt;
使用 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");