|
using System;
using System.Collections.Generic;
using System.Text;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.Reflection;
namespace CreateDelegate
{
//public interface IPrint
//{
// void Print();
//}
class Program
{
static void Main( string[] args )
{
Test1();
Test2();
Test3();
}
private static void Test1()
{
//
// Create an instance of type Foo and call Print
//
string FooSource = @"
class Foo
{
public void Print()
{
System.Console.WriteLine(""Hello from class Foo"");
}
}";
Assembly assembly = CompileSource(FooSource);
object myFoo = assembly.CreateInstance("Foo");
//myFoo.Print(); // - Print not a member of System.Object
//((Foo)myFoo).Print(); // - Type Foo unknown
Console.WriteLine("Can not call Print on type object.");
}
private static void Test2()
{
//
// Create an instance of type FooLibrary.IPrint and call Print
//
string FooInterface = @"
class Foo : FooLibrary.IPrint {
public void Print() {
System.Console.WriteLine(""Hello from class Foo"");
}
}";
Assembly assembly = CompileSource(FooInterface);
//foo = (FooLibrary.IPrint)assembly.CreateInstance("FooLibrary.IPrint",false,BindingFlags.FlattenHierarchy,null,null,null,null);
Type fType = assembly.GetTypes()[0];
Type iType = fType.GetInterface("FooLibrary.IPrint");
//if (iType.FullName == "FooLibrary.IPrint")
if (iType != null)
{
FooLibrary.IPrint foo = (FooLibrary.IPrint)assembly.CreateInstance(fType.FullName);
foo.Print();
}
}
delegate void PrintDelegate();
private static void Test3()
{
//
// Get a PrintDelegate from an instance of the type Foo.
//
string FooSourcHeader = @"
using System;
class Foo {
static public void Print()
{";
string FooSourceFooter = @"
}
}";
string myPrint = FooSourcHeader
+ @"Console.WriteLine(""Hello from Print delegate"");"
+ FooSourceFooter;
Assembly assembly = CompileSource(myPrint);
//
// Try to Invoke a method
//
Type fooType = assembly.GetType("Foo");
MethodInfo printMethod = fooType.GetMethod("Print");
PrintDelegate fooPrint = (PrintDelegate)Delegate.CreateDelegate(typeof(PrintDelegate), printMethod);
fooPrint();
}
private static Assembly CompileSource( string sourceCode )
{
CodeDomProvider cpd = new CSharpCodeProvider();
CompilerParameters cp = new CompilerParameters();
cp.ReferencedAssemblies.Add("System.dll");
cp.ReferencedAssemblies.Add("ClassLibrary1.dll");
cp.GenerateExecutable = false;
// Invoke compilation.
CompilerResults cr = cpd.CompileAssemblyFromSource(cp, sourceCode);
return cr.CompiledAssembly;
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.