日期:2008-08-28 浏览次数:20482 次
要利用.NET语言(例如:c# vb.net)开发自己的脚本语言必须实现2步:
1.能够动态编译.NET 源代码
2.动态调用.NET组件
首先我们介绍下动态条用.NET组件
1.新建1个工程作为组件接口DynamicInterface
创建新的类:
using System;
namespace DynamicInterface
{
public interface IDynamic {
string getString();
}
}
2.新建1个工程作为需要动态调用的组件DynamicClass
引用DynamicInterface
创建新的类:
using System;
namespace DynamicCls
{
public class DynamicClass:DynamicInterface.IDynamic //实现接口
{
public DynamicClass()
{
}
#region IDynamic 成员
public string getString() {
// TODO: 添加 DynamicClass.getString 实现
return "Hello World Huhong";
}
#endregion
}
3.新建1个工程来动态调用DynamicClass
using System;
using System.Reflection;
using System.Threading;
namespace dynamicreference
{
class DynamicReference
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
string dllfilename=@"C:\DynamicClass.dll";
Thread.GetDomain().AssemblyLoad+=new AssemblyLoadEventHandler(DynamicReference_AssemblyLoad);
Thread.GetDomain().AssemblyResolve+=new ResolveEventHandler(DynamicReference_AssemblyResolve);
Assembly asm=System.Reflection.Assembly.LoadFile(dllfilename);
Type type=asm.GetType("DynamicCls.DynamicClass",true);
Object oh=Activator.CreateInstance(type);
MethodInfo mi = type.GetMethod("getString");
Console.WriteLine(mi.Invoke(oh,null).ToString()); //利用反射机制运行
DynamicInterface.IDynamic id=(DynamicInterface.IDynamic)oh; //利用接口运行
Console.WriteLine(id.getString());
}
private static void DynamicReference_AssemblyLoad(object sender, AssemblyLoadEventArgs args) {
Console.WriteLine("加载1个组件:"+args.LoadedAssembly.FullName );
}
private static Assembly DynamicReference_AssemblyResolve(object sender, ResolveEventArgs args) {
Console.WriteLine("组件解析失败!");
return null;
}
}
}
未完待续....