要利用.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 [email protected]"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;
}
}
}
未完待续....
新闻热点
疑难解答
图片精选