动态的Compact Framework C#加载DLL [英] Compact Framework C# loading DLL dynamically

查看:169
本文介绍了动态的Compact Framework C#加载DLL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

而不是在我的项目中添加一个dll文件作为参考,我需要动态地使用这个dll文件中特定命名空间的一些类。

instead of including a dll file in my project as a reference, I need to dynamically use some classes from specific namespaces in that dll file.

一些有关该主题的研究,并通过使用Activator,InvokeMember等来找到方法。

I've done some research about the topic and found the way to do that by using Activator, InvokeMember and so on.

但是,我写一个正确的代码有问题。我需要这样做:

But, i have a problem with writing proper code. I need to do something like:

A a = new A();

B[] b = a.method();

B b0 = b[0];

其中A和B是动态加载的dll文件中命名空间中类的类型。

where A and B are type of classes from namespace in dynamically loaded dll file.

我正在调整这段代码:

var DLL = Assembly.Load(path_to_dll);

//here variables to use later

foreach(Type type in DLL.GetTypes())
{
    //here checking if type is what I want and:
    var c = Activator.CreateInstance(type);
    type.InvokeMember("method", BindingFlags.InvokeMethod, null, c, null);
}

我不知道如何使用InvokeMember返回DLL中指定的数组类型。另外我需要两个未知类型的变量(在运行时被称为)可以在整个方法块中看到。

I don't know how to use InvokeMember to return array of specified in DLL type. In addition I need two variables of unknown type (which be known in runtime) to be visible in whole method block.

请给我一些提示。

推荐答案

正常调用成员,但可以将结果转换为 IList

Invoking the member is done as normal - but you can then cast the result to IList:

IList array = (IList) type.InvokeMember(...);
object firstElement = array[0];

(所有数组都执行 IList Array 中略微使用)。

(All arrays implement IList, which is slightly simper to use in this case than Array.)

不能使用实际的类型作为类型的变量,因为你在编译时不了解它。如果您知道该类型将实现您可以访问的一些适当的界面,可以使用以下方式:

You can't use the actual type as the type of the variable, because you don't know about it at compile-time. If you know that the type will implement some appropriate interface which you have access to, you could use that:

IFoo firstElement = (IFoo) array[0];

这篇关于动态的Compact Framework C#加载DLL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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