在运行时 C# 中编译自定义方法



>我想在运行时在我的项目中编译一个 c# 类或方法。 我可以在运行时编译我的方法,但不幸的是我无法编译复杂的方法运行时或从数据库中检索数据。

我使用此代码并且效果很好:

string sourceCode = @"
public class Calc_Class { 
public int Rent (int parameter , int a) {
int b= 20 ;
if(a+parameter > 10 ){ 
return parameter+3;
}
return parameter += 42;
}
}";
string sourceCode2 = @"
public class Calc_Class { 
public int Rent (int parameter , int a) {
int b= 20 ;
if(a+parameter > 10 ){ 
for(int i=0;i<5;i++){
parameter = parameter+i;
}
retrun parameter;
}
return parameter += 42;
}
}";
var compParms = new CompilerParameters
{
GenerateExecutable = false,
GenerateInMemory = true
};
var csProvider = new CSharpCodeProvider();
CompilerResults compilerResults = csProvider.CompileAssemblyFromSource(compParms,    sourceCode);
object typeInstance =  compilerResults.CompiledAssembly.CreateInstance("Calc_Class");
MethodInfo mi = typeInstance.GetType().GetMethod("Rent");
int methodOutput = (int)mi.Invoke(typeInstance, new object[] { 1, 19 });
textBox2.Text = methodOutput.ToString();

如果我调用源代码,它会很好地工作,但源代码 2 有一个错误 如:无法加载文件或程序集"file://AppData\本地\Temp\v4nza4bk.dll"或其依赖项之一。系统找不到指定的文件

每次运行我的项目后,DLL名称将被更改。 如何解决此问题?

您可以修复使用CompilerParameters编译的dll的名称,请指定OutputAssembly:

CompilerParameters compParms = new CompilerParameters();
compParms.OutputAssembly = @"d:NameAssembly.dll";

或在 compParms 初始化期间添加该选项。

你在源代码2上有拼写错误

重新运行--->返回

确实,该消息没有帮助... 但是如果你修复了拼写错误,你的代码工作正常!

关于连接字符串错误: 以下方法将源代码粘贴到... 如果将其复制粘贴到 C# 中,您将看到有很多错误需要修复。 首先修复这些问题,并使其作为一种方法运行良好。

void SourceCode3()
{
string connection = Data Source =.;
Initial Catalog = TestReport;
Integrated Security = True;
using (SqlConnection con = new SqlConnection(connection))
{
using (SqlCommand cmd = new SqlCommand(SELECT * from FormulaOne))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
sdr.Read();
textBox2.Text = sdr[Formula].ToString();
}
con.Close();
}
}
}

我希望你会达到这样的东西:

System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = "Data Source=.; Initial Catalog=TestReport; Integrated Security = True;";
con.Open();
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("SELECT * from FormulaOne");
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
System.Data.SqlClient.SqlDataReader sdr = cmd.ExecuteReader();
sdr.Read();
textBox2.Text = sdr["Formula"].ToString();
con.Close();

为了使它成为一个字符串,请记住您需要在每个".

希望这对你有帮助

最新更新