Đọc this (trích dẫn sau).
Điều đó là có thể: hãy xem System.CodeDom
và System.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;
}
}
}
Tôi có thể truy vấn lý do bạn muốn không? – dotalchemy
http://scriptcs.net/? :) – NicoJuicy