C# 在C中动态加载类#

C# 在C中动态加载类#,c#,dll,C#,Dll,我试图加载一个类(比如Class1:Interface),而不知道它的名称。 我的代码如下所示: Assembly a = Assembly.LoadFrom("MyDll.dll"); Type t = (Type)a.GetTypes()[0]; (Interface) classInstance = (Interface) (ClasActivator.CreateInstance(t); 根据我在网上找到的文章和MSDN,GetTypes()[0]应该返回Class1(MyDll.dl

我试图加载一个类(比如Class1:Interface),而不知道它的名称。 我的代码如下所示:

Assembly a = Assembly.LoadFrom("MyDll.dll");
Type t = (Type)a.GetTypes()[0];
(Interface) classInstance = (Interface) (ClasActivator.CreateInstance(t);
根据我在网上找到的文章和MSDN,
GetTypes()[0]
应该返回Class1(MyDll.dll中只有一个类)。但是,我的代码返回
Class1.Properties.Settings
。因此第3行创建了一个异常:

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

我真的不知道为什么以及如何解决这个问题。

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

Type t = a.GetTypes()
  .FirstOrDefault(type => type.GetInterface(typeof(Interface).FullName) != null);

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

Type t = a.GetTypes()
  .FirstOrDefault(type => type.GetInterface(typeof(Interface).FullName) != null);

程序集可以容纳多个类型(您可能在dll中有一个
Settings.Settings
文件,它在
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
    }
}

程序集可以容纳多个类型(您可能在dll中有一个
Settings.Settings
文件,它在
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
    }
}

根据您尝试执行的操作,您可以使用属性标记原始接口,然后检查具有该属性的所有类型。根据您尝试执行的操作,您可以使用属性标记原始接口,然后检查具有该属性的所有类型。我可能建议使用
Single
,因为在程序集中似乎应该有一个,而且只有一个这样的类。我可能建议使用
Single
,因为在程序集中似乎应该有一个,而且只有一个这样的类。工作起来很有魅力!Thx@Martin与其说谢谢,不如像个魔术师一样工作!Thx@Martin与其说谢谢,