【问题标题】:How to use Activator.CreateInstance to instantiate an external class?如何使用 Activator.CreateInstance 实例化外部类?
【发布时间】:2012-12-20 14:19:48
【问题描述】:

我有一个应用程序,我想在其中实例化一个完全在应用程序之外的类,可能是在以后由第三方编写的。所以类不能知道,但类中的接口是已知的。所以我想使用后期绑定。

在我的代码 (VB.NET) 中,我有以下内容:

Dim a As Object
a = Activator.CreateInstance("MyNameSpace.CustomClass", "")
MsgBox(a.Name)

我在第二行出现异常:Could not load file or assembly 'MyNameSpace.CustomClass' or one of its dependencies. The system cannot find the file specified.,即使程序集与可执行文件位于同一文件夹中。我不能使用 Type.GetType(),因为调用程序集不知道该类型。

【问题讨论】:

    标签: vb.net instantiation late-binding


    【解决方案1】:

    您需要CreateInstanceFrom 方法。

        var typeReference = Activator.CreateInstanceFrom(assemblyPath, 
                                                           fullyQualifiedClassName);
    

    但是,对我来说,MEF 会是一个更好的解决方案,因为您可以在界面上绑定 Import/Export。

    【讨论】:

    猜你喜欢
    • 2014-06-18
    • 1970-01-01
    • 1970-01-01
    • 2015-10-14
    • 1970-01-01
    • 1970-01-01
    • 2012-02-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多