1

I am trying to load a class (say Class1:Interface ) without knowing its name from an assembly. My code looks like this:

Assembly a = Assembly.LoadFrom("MyDll.dll");
Type t = (Type)a.GetTypes()[0];
(Interface) classInstance = (Interface) (ClasActivator.CreateInstance(t);

Based on the articles I found online and MSDN, GetTypes()[0] is suppose to return Class1 (there is only one class in MyDll.dll). However, my code returns Class1.Properties.Settings. So line 3 creates an exception:

Unable to cast object of type 'Class1.Properties.Settings' to type Namespace.Interface'.

I really do not know why and how to fix this problem.

4

2 回答 2

3

程序集可以容纳多种类型(您可能Settings.settings在 dll 中有一个文件,它在文件的内部创建了一个类Settings.Designer.cs),您只能在代码中获得第一个类,在您的情况下,它是Settings类,您需要浏览所有类型并搜索具有所需界面的类型。

Assembly asm = Assembly.LoadFrom("MyDll.dll");
Type[] allTypes = asm.GetTypes();
foreach (Type type in allTypes)
{
    // Only scan objects that are not abstract and implements the interface
    if (!type.IsAbstract && typeof(IMyInterface).IsAssignableFrom(type));
    {
        // Create a instance of that class...
        var inst = (IMyInterface)Activator.CreateInstance(type);

        //do your work here, may be called more than once if more than one class implements IMyInterface
    }
}
于 2013-08-19T18:48:33.613 回答
2

只需检查以找到实现接口的第一个:

Type t = a.GetTypes()
  .FirstOrDefault(type => type.GetInterface(typeof(Interface).FullName) != null);
于 2013-08-19T18:47:38.650 回答