C# 如何执行字符串中的代码?
假设我有这样的东西:C# 如何执行字符串中的代码?,c#,C#,假设我有这样的东西: string singleStatement = "System.DateTime.Now"; 有什么方法可以获取singleStatement并在运行时解析和运行它吗 以便: DateTime currentTime = singleStatement.SomeCoolMethodToRunTheText(); 将DateTime.Now的值分配给currentTime这只能通过使用编译器服务和Reflection.Emit()进行编译、汇编并加载到内存中 看看这里
string singleStatement = "System.DateTime.Now";
有什么方法可以获取singleStatement
并在运行时解析和运行它吗
以便:
DateTime currentTime = singleStatement.SomeCoolMethodToRunTheText();
将
DateTime.Now
的值分配给currentTime
这只能通过使用编译器服务和Reflection.Emit()
进行编译、汇编并加载到内存中
看看这里
您可以在运行时使用CSharpCodeProvider对象编译代码。您是否真的想这样做还有待讨论。:-) 阅读(引用如下) 这是可能的:看看
System.CodeDom
和System.CodeDom.Compiler
我发现了几个月前写的一个例子:
假设usingList
是一个arraylist
和all-use语句(不使用
关键字,System.Xml
例如)
假设importList
是一个arraylist
,其中包含了
编译(例如,system.dll
)
假设source
是要编译的源代码
假设classname
是要编译的类的名称
假设methodname
是方法的名称
查看以下代码:
//Create method
CodeMemberMethod pMethod = new CodeMemberMethod();
pMethod.Name = methodname;
pMethod.Attributes = MemberAttributes.Public;
pMethod.Parameters.Add(new
CodeParameterDeclarationExpression(typeof(string[]),"boxes"));
pMethod.ReturnType=new CodeTypeReference(typeof(bool));
pMethod.Statements.Add(new CodeSnippetExpression(@"
bool result = true;
try
{
" + source + @"
}
catch
{
result = false;
}
return result;
"));
//Crée la classe
CodeTypeDeclaration pClass =
new System.CodeDom.CodeTypeDeclaration(classname);
pClass.Attributes = MemberAttributes.Public;
pClass.Members.Add(pMethod);
//Crée le namespace
CodeNamespace pNamespace = new CodeNamespace("myNameSpace");
pNamespace.Types.Add(pClass);
foreach(string sUsing in usingList)
pNamespace.Imports.Add(new
CodeNamespaceImport(sUsing));
//Create compile unit
CodeCompileUnit pUnit = new CodeCompileUnit();
pUnit.Namespaces.Add(pNamespace);
//Make compilation parameters
CompilerParameters pParams =
new CompilerParameters((string[])importList.ToArray(typeof(string)));
pParams.GenerateInMemory = true;
//Compile
CompilerResults pResults =
(new CSharpCodeProvider())
.CreateCompiler().CompileAssemblyFromDom(pParams, pUnit);
if (pResults.Errors != null && pResults.Errors.Count>0)
{
foreach(CompilerError pError in pResults.Errors)
MessageBox.Show(pError.ToString());
result =
pResults.CompiledAssembly.CreateInstance("myNameSp ace."+classname);
}
比如说,
if 'usingList' equals
{
"System.Text.RegularExpressions"
}
if 'importList' equals
{
"System.dll"
}
if 'classname' equals "myClass"
if 'methodName' equals "myMethod"
if 'source' equals "
string pays=@"ES
FR
EN
"
Regex regex=new Regex(@"^[A-Za-z]
{
2
}
$");
result=regex.IsMatch(boxes[0]);
if (result)
{
regex=new Regex(@"^"+boxes[0]+@".$",RegexOptions.Multiline);
result=regex.Matches(pays).Count!=0;
}
然后,将编译的代码如下所示:
using System.Text.RegularExpressions;
namespace myNameSpace
{
public class myClass
{
public bool myMethod(string[] boxes)
{
bool result=true;
try
{
string pays=@"ES
FR
EN
"
Regex regex=new Regex(@"^[A-Za-z]
{
2
}
$");
result=regex.IsMatch(boxes[0]);
if (result)
{
regex=new Regex(@"^"+boxes[0]+@".$",RegexOptions.Multiline);
result=regex.Matches(pays).Count!=0;
}
}
catch
{
result=false;
}
return result;
}
}
}
我能问一下你为什么想这么做吗??)