2011-01-26 51 views
10

Nói rằng tôi có một cái gì đó như thế này:Làm cách nào để thực thi mã có trong chuỗi?

string singleStatement = "System.DateTime.Now"; 

Có một số cách để chăm singleStatement và phân tích và chạy nó tại thời gian chạy?

Vì vậy mà:

DateTime currentTime = singleStatement.SomeCoolMethodToRunTheText(); 

sẽ gán giá trị của DateTime.Now để currentTime.

+1

Tôi có thể truy vấn lý do bạn muốn không? – dotalchemy

+1

http://scriptcs.net/? :) – NicoJuicy

Trả lời

-1

Bạn có thể biên dịch mã lúc thực thi bằng cách sử dụng một đối tượng CSharpCodeProvider. Cho dù bạn thực sự muốn làm điều này hay không là cho cuộc tranh luận. :-)

1

Đọc this (trích dẫn sau).

Điều đó là có thể: hãy xem System.CodeDomSystem.CodeDom.Compiler.

Tôi đã tìm thấy một ví dụ tôi đã viết cách đây vài tháng: giả usingList là một arraylist với tất cả sử dụng statement (mà không sử dụng từ khóa, System.Xml ví dụ) giả importList là một arraylist với tất cả các tên dll đó là cần thiết cho biên soạn (system.dll ví dụ) giả source là mã nguồn mà bạn muốn biên dịch giả classname là tên của lớp bạn muốn biên dịch giả methodname là tên của phương pháp

Hãy nhìn vào đoạn mã sau:

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

Ví dụ,

if 'usingList' equals 
{ 
    "System.Text.RegularExpressions" 
} 
if 'importList' equals 
{ 
    "System.dll" 
} 
if 'classname' equals "myClass" 
if 'methodName' equals "myMethod" 
if 'source' equals " 
string [email protected]"ES 
FR 
EN 
" 
Regex regex=new Regex(@"^[A-Za-z] 
{ 
    2 
} 
$"); 
result=regex.IsMatch(boxes[0]); 
if (result) 
{ 
    regex=new Regex(@"^"+boxes[0][email protected]".$",RegexOptions.Multiline); 
    result=regex.Matches(pays).Count!=0; 
} 

Sau đó, mã sẽ được biên soạn sẽ được như sau:

using System.Text.RegularExpressions; 
namespace myNameSpace 
{ 
    public class myClass 
    { 
     public bool myMethod(string[] boxes) 
     { 
      bool result=true; 
      try 
      { 
       string [email protected]"ES 
       FR 
       EN 
       " 
       Regex regex=new Regex(@"^[A-Za-z] 
       { 
        2 
       } 
       $"); 
       result=regex.IsMatch(boxes[0]); 
       if (result) 
       { 
        regex=new Regex(@"^"+boxes[0][email protected]".$",RegexOptions.Multiline); 
        result=regex.Matches(pays).Count!=0; 
       } 
      } 
      catch 
      { 
       result=false; 
      } 
      return result; 
     } 
    } 
} 
+1

Trong khi liên kết này có thể trả lời câu hỏi, tốt hơn nên bao gồm các phần thiết yếu của câu trả lời ở đây và cung cấp liên kết để tham khảo. Câu trả lời chỉ liên kết có thể trở thành không hợp lệ nếu trang được liên kết thay đổi. – CodeLikeBeaker

+0

@JasonHeine u hiểu rồi – Shimmy

Các vấn đề liên quan