Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/85.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何执行字符串中的代码?_C# - Fatal编程技术网

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

我能问一下你为什么想这么做吗??)