The string variable 'str' contains code that will be compiled on the fly
and executed. For a simpler example,
let me know if this is what you meant by dynamic code.
You will need to compile the "base.dll" separately and modify the path
as well. Base.dll could be a simple class with a constructor.
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Windows.Forms;
using System;
using System.Reflection;
public class t
{
static void Main(){
Base myobj;
CSharpCodeProvider csp= new CSharpCodeProvider();
ICodeCompiler ic = csp.CreateCompiler();
CompilerParameters cparam= new CompilerParameters();
cparam.GenerateInMemory = true;
cparam.GenerateExecutable = false;
cparam.ReferencedAssemblies.Add("system.dll");
cparam.ReferencedAssemblies.Add(@"c:\c#_prgs\base. dll");
string str = "using System;"+
"class myclass" +
"{"+
"public myclass(){i=123;}"+
"public int i;"+
"public string ToString()"+
"{"+
"return i.ToString();"+
"}" +
"}";
CompilerResults cres= ic.CompileAssemblyFromSource(cparam,str);
foreach (CompilerError ce in cres.Errors)
MessageBox.Show(ce.ErrorText);
if (cres.Errors.Count == 0 && cres.CompiledAssembly != null)
{
Type ObjType = cres.CompiledAssembly.GetType("myclass");
try
{
if (ObjType != null)
{
myobj = (Base)Activator.CreateInstance(ObjType);
Console.WriteLine(myobj.ToString());
FieldInfo[] f= ObjType.GetFields();
foreach(FieldInfo ff in f)
{
MessageBox.Show(ff.Name + "=" + ff.GetValue(myobj).ToString());
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
with regards,
J.V.Ravichandran
-
http://www.geocities.com/
jvravichandran
- Or, just search on "J.V.Ravichandran"
at
http://www.Google.com
*** Sent via Developersdex
http://www.developersdex.com ***