开发者

Dynamically load a type from an external assembly

开发者 https://www.devze.com 2022-12-25 02:30 出处:网络
From managed code, how do I load a managed type from another assembly at runtime, assuming the calling code does not have a static reference to the assembly?

From managed code, how do I load a managed type from another assembly at runtime, assuming the calling code does not have a static reference to the assembly?

To clarify, let's say I have class Lib in Lib.cs compiled into Lib.dll. I want to write a class Foo in a separate assembly called Foo.dll, that does not have a reference to Lib.dll statically, but instead loads Lib.dll and then reflects on for the presence of the class Lib and then calls a method on it.

Sorry for such an obvious question on Reflection. I figure it'll take much开发者_运维技巧 lesser time to get the answer on a forum that to read a few articles.


Here is a short snippet:

Assembly assembly = Assembly.LoadFile("Lib.dll");
ILib lib = (ILib)assembly.CreateInstance("Lib");
lib.doSomething();

Of course the Lib class must implement the ILib interface which must be accessible both from Foo.dll and Lib.dll. This way you achieve abstraction.

0

精彩评论

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

关注公众号