C# 是否在运行时加载从当前程序集继承类的类型?

C# 是否在运行时加载从当前程序集继承类的类型?,c#,.net,inheritance,reflection,system.reflection,C#,.net,Inheritance,Reflection,System.reflection,当我在运行时加载一个程序集,该程序集包含一个继承将要加载该程序集的程序中定义的类的类时,我是否可以将该对象转换并存储为继承的抽象类的实例 public class ExternalService : Service { string assemblyPath, className; Service service; public ExternalService(string address, string title, string httpMethode, bool t

当我在运行时加载一个程序集,该程序集包含一个继承将要加载该程序集的程序中定义的类的类时,我是否可以将该对象转换并存储为继承的抽象类的实例

public class ExternalService : Service {
    string assemblyPath, className;
    Service service;
    public ExternalService(string address, string title, string httpMethode, bool takesArguments,string assemblyPath,string className) : base(address, title, httpMethode, takesArguments) {
        this.assemblyPath = assemblyPath;
        this.className = className;
        var assembly = Assembly.LoadFile(assemblyPath);
        foreach(Type type in assembly.GetExportedTypes()) {
            if (type.Name == className) {
                dynamic c = Activator.CreateInstance(type);
                if(c is Service) {
                    Service s = c as Service;
                    s.Address = address;
                    s.HttpMethode = httpMethode;
                    s.Title = title;
                    s.TakesArguments = takesArguments;
                    service = s;
                    break;
                }
            }
        }
    }

    public override void Handle(ServiceContextEventArgs e) {
        service.Handle(e);
    }
}
已解决:


这很有效。

“我可以将该对象转换为继承的抽象类的实例并存储吗?”您尝试过吗?结果如何?这是一个好问题。老实说,我不太想知道,但我想知道,因为我正在开发一个相当耗时的图书馆,这是其中的一部分。当我读你的文章时,听起来有点像鸡和蛋的问题。加载的程序集如何知道您已定义了它继承的类?或者,您的意思是您有一个加载类继承自的类型变量?发布的代码是加载类的代码还是加载程序集的程序的代码?SHS.dll库中有服务类,现在,如果导入该库并编写一个继承另一个库中服务类的类“Foo”,比如SHSE.dll,那么我可以在运行时导入SHSE.dll并创建Foo实例并强制转换为服务实例,将其存储在ExternalService类的实例中吗?这是加载程序集的程序,它与服务类位于同一程序集中