开发者

How to calling a function in a .net dll through an interface loaded through reflection

Hello I'll try my best to explain this.

Basically, I am loading a library through reflection using the Assembly.LoadFile.

From there I have an interface IFace that defines a method "GetStrings" that returns an array of strings.

The dynamically loaded DLL has a class named "Class1" that implements IFace.

I need a way to call this interfaced method 开发者_JAVA百科through the dynamically loaded lib. I'd like to keep it tightly coupled, which leaves me wondering what to do. I know I can use MethodInvoker to call the method, but I'm trying to find a way I can do something like this:

IFace obj = (IFace)ReflectionAssembly.Class1;
string[] strs = obj.GetStrings();

Any ideas?


Something like:

    var assm = Assembly.Load("ClassLibrary1");
    var type = assm.GetType("ClassLibrary1.Class1");
    var instance = Activator.CreateInstance(type) as IFace;
    string[] strings = instance.GetStrings();


Use Assembly.CreateInstance() to create the object, pass it a 'well known name'. Cast the return value to IFace, the rest is easy. Oh, don't use LoadFile, use LoadFrom.


Once you have the Type via Reflection (using something like Assembly.GetType), you can use Activator.CreateInstance:

IFace obj = (IFace)Activator.CreateInstance(class1Type);
string[] strs = obj.GetStrings();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜