[加载DLL并在运行时动态创建接口实现的实例

问题描述 投票:0回答:1

我有很多DLL连接器。每个DLL内部都有太多方法。但是每个DLL连接器都包含以下两种方法(byte [] Document = GetDocument(字符串,字符串,字符串);和byte [] Image = GetImage(字符串,字符串,字符串);)。

我想做的是:1-在运行时选择DLL文件。2-填充三个字符串。3-将三个字符串传递到插入的DLL内的方法(上面提到的)以接收返回的文件。

我只想知道如何在DLL中调用方法。

感谢您的帮助。

c# dll load
1个回答
0
投票

(当然,您必须使用反射。看看Assembly类。

您可以例如使用AssemblyAssembly.LoadFile加载程序集。要激活组件中包含的类型以调用其成员,可以使用Assembly.LoadFrom

Assembly.CreateInstance

如果构造函数需要参数,则可以使用适当的Assembly assembly = Assembly.LoadFile("C:\bin\runtime.dll"); TypeInsideAssembly instanceOfTypeInsideAssembly = (TypeInsideAssembly) assembly.CreateInstance(typeOf(TypeInsideAssembly)); instanceOfTypeInsideAssembly.InvokeMethod(params); overload

示例

以下通用示例使用反射来创建位于指定程序集中的CreateInstance(String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[])实例,并期望使用无参数构造函数。 TBase可以是一个类(基类)或接口。不是TBase或未定义无参数构造函数的类型将被忽略。

public

用法

private IEnumerable<TBase> GetInstancesOf<TBase>(string assemblyFilePath)
{
  var assembly = Assembly.LoadFile(assemblyFilePath);
  Type[] publicTypes = assembly.GetExportedTypes();

  // Filter and return all public types in assembly...
  IEnumerable<TBase> documentProviders = publicTypes

    // ...that are not an interface (as we can't create instances of interfaces)...
    .Where(publicType => !publicType.IsInterface 

      // ...AND that have a public parameterless constructor...
      && publicType.GetConstructor(Type.EmptyTypes) != null 

      // ...AND are a subtype of TBase 
      && typeof(TBase).IsAssignableFrom(publicType))

    // Take each collected type and create an instance of those types
    .Select(concreteInterfaceType => assembly.CreateInstance(concreteInterfaceType.FullName))

    // Since CreateInstance() returns object, cast each created instance to the common subtype TBase
    .Cast<TBase>();

  return documentProviders;
}
© www.soinside.com 2019 - 2024. All rights reserved.