如何调用C#中的托管DLL文件? [英] How to call a Managed DLL File in C#?

查看:427
本文介绍了如何调用C#中的托管DLL文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一种脚本语言,但我有一个严重的问题。



我需要这样做,所以你可以使用语言调用.NET DLL,但是我没有找到在C#中没有办法。



有没有人知道如何以编程方式加载和调用.NET DLL? (我不能只是添加引用,所以不要这样说)

解决方案

这是我做的:

  Assembly assembly = Assembly.LoadFrom(assemblyName); 
System.Type type = assembly.GetType(typeName);
Object o = Activator.CreateInstance(type);
IYourType yourObj =(o as IYourType);

其中 assemblyName typeName 是字符串,例如:

  string assemblyName = @C:\foo\\ \\yourDLL.dll; 
string typeName =YourCompany.YourProject.YourClass; //完全限定类型名称

那么你可以调用obj上的方法:

  yourObj.DoSomething(someParameter); 

当然,您可以调用哪些方法由界面定义 IYourType ...


I am making a scripting language but I have a serious problem.

I need to make it so you can call .NET DLLs in the language but I have found no way to do this in C#.

Does any one know how can I load and call a .NET dll programmatically? (I can not just Add reference so don't say that)

解决方案

Here's how I did it:

Assembly assembly = Assembly.LoadFrom(assemblyName);
System.Type type = assembly.GetType(typeName);
Object o = Activator.CreateInstance(type);
IYourType yourObj = (o as IYourType);

where assemblyName and typeName are strings, for example:

string assemblyName = @"C:\foo\yourDLL.dll";
string typeName = "YourCompany.YourProject.YourClass";//a fully qualified type name

then you can call methods on your obj:

yourObj.DoSomething(someParameter);

Of course, what methods you can call is defined by your interface IYourType...

这篇关于如何调用C#中的托管DLL文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆