【问题标题】:How to call a Managed DLL File in C#?如何在 C# 中调用托管 DLL 文件?
【发布时间】:2011-07-26 13:19:51
【问题描述】:

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

我需要这样做,以便您可以使用该语言调用 .NET DLL,但我发现无法在 C# 中执行此操作。

有谁知道如何以编程方式加载和调用 .NET dll? (我不能只是添加参考所以不要这么说)

【问题讨论】:

  • 为什么添加引用不起作用?
  • 因为我是脚本语言,所以用户需要能够调用与interrupter放在同一目录下的任何DLL

标签: c# dll call external managed


【解决方案1】:

我是这样做的:

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定义的...

【讨论】:

  • 有时为加载的程序集创建一个单独的应用程序域是个好主意,这意味着您可以在完成后将其丢弃。
  • 你是如何在项目中不引用 DLL 的情况下引用 IYourType 的?
【解决方案2】:

您可以使用Assembly.LoadFrom,从那里使用标准reflection 来获取类型和方法(我假设您已经在脚本中这样做了)。 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());
}

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-01
      • 2023-03-24
      • 2011-03-04
      • 1970-01-01
      • 2018-02-10
      • 1970-01-01
      • 2021-03-28
      相关资源
      最近更新 更多