Compact Framework C# loading DLL dynamically

你离开我真会死。 提交于 2019-12-11 18:57:33

问题


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.

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];

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

I'm trying to adjust that piece of code:

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);
}

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.

Please give me some tips.


回答1:


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];

(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];


来源:https://stackoverflow.com/questions/21411752/compact-framework-c-sharp-loading-dll-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!