in my application, I want to change class B at startup, here is my code but apparently the new class B is not changed. I join a sample code that is not the final application to show the problem, sorry for my bad english Where is th problem? How to please? in my application, I want to change class B at startup, here is my code but apparently the new class B is not changed. I join a sample code that is not the final application to show the problem, sorry for my bad english Where is th problem? How to please?
namespace TestRecompile
{
class Program
{
static void Main(string[] args)
{
A test = new A();
ModifiyClassB();
test = new A();
Console.ReadKey();
}
static void ModifiyClassB()
{
string[] code = {
"using System; using System.Data;" +
"namespace TestRecompile"+
"{" +
"public class B " +
"{" +
"protected int id = 0;"+
"public B()"+
"{"+
"id = 3;"+
"}"+
"}" +
"}"
};
CompileAndRun(code);
}
static int CompileAndRun(string[] code)
{
CompilerParameters CompilerParams = new CompilerParameters();
string outputDirectory = Directory.GetCurrentDirectory();
CompilerParams.GenerateInMemory = true;
CompilerParams.TreatWarningsAsErrors = false;
CompilerParams.GenerateExecutable = false;
CompilerParams.CompilerOptions = "/optimize";
string[] references = { "System.dll", "System.Data.dll" };
CompilerParams.ReferencedAssemblies.AddRange(references);
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerResults compile = provider.CompileAssemblyFromSource(CompilerParams, code);
if (compile.Errors.HasErrors)
{
string text = "Compile error: ";
foreach (CompilerError ce in compile.Errors)
{
text += "rn" + ce.ToString();
}
throw new Exception(text);
}
Module module = compile.CompiledAssembly.GetModules()[0];
Type mt = null;
MethodInfo methInfo = null;
if (module != null)
{
mt = module.GetType("CodeFromFile.CodeFromFile");
}
if (mt != null)
{
methInfo = mt.GetMethod("Add");
}
if (methInfo != null)
{
return (int)methInfo.Invoke(null, new object[] { 5, 10 });
}
return -1;
}
}
public class B
{
protected int id = 0;
public B()
{
id = 2;
}
}
public class A : B
{
public A()
{
Console.WriteLine("id value is:" + id);
}
}
}
Aucun commentaire:
Enregistrer un commentaire