如何在c#中调用托管DLL文件

本文关键字:DLL 文件 调用 | 更新日期: 2023-09-27 18:03:26

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

我需要这样做,所以你可以在语言中调用。net dll,但我发现没有办法在c#中做到这一点。

有谁知道我如何加载和调用。net dll编程?(我不能直接添加引用,所以不要这么说)

如何在c#中调用托管DLL文件

我是这样做的:

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

其中assemblyNametypeName为字符串,例如:

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

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

yourObj.DoSomething(someParameter);

当然,你可以调用的方法是由你的接口IYourType定义的…

您可以使用程序集。LoadFrom,从那里使用标准反射来获得类型和方法(我假设你已经在脚本中这样做了)。MSDN页面上的示例(链接)显示如下:

Assembly SampleAssembly;
SampleAssembly = Assembly.LoadFrom("c:''Sample.Assembly.dll");
// Obtain a reference to a method known to exist in assembly.
MethodInfo Method = SampleAssembly.GetTypes()[0].GetMethod("Method1");
// Obtain a reference to the parameters collection of the MethodInfo instance.
ParameterInfo[] Params = Method.GetParameters();
// Display information about method parameters.
// Param = sParam1
//   Type = System.String
//   Position = 0
//   Optional=False
foreach (ParameterInfo Param in Params)
{
    Console.WriteLine("Param=" + Param.Name.ToString());
    Console.WriteLine("  Type=" + Param.ParameterType.ToString());
    Console.WriteLine("  Position=" + Param.Position.ToString());
    Console.WriteLine("  Optional=" + Param.IsOptional.ToString());
}

听起来您需要使用Assembly的重载之一。负载(组装。在MSDN上加载)。动态加载程序集后,可以使用System。反射、动态对象和/或接口/基类来访问其中的类型