一个类可以继承一个未引用的程序集吗?或者它可能是自我实现的?
我希望能够动态加载未引用的dll并将其设置为自身 - 例如:
Public Class MyProject.SomeClassWrapper
Inherits System.Windows.Forms.AxHost
Public Sub New()
Dim dynamicallyLoadedAssembly As System.Reflection.Assembly = System.Reflection.Assembly.LoadFile("C:\Temp\SomeLibrary.dll")
Me = dynamicallyLoadedAssembly.CreateInstance("SomeLibrary.SomeClass") '<----- Doesn't work, but is there a way to do this?
End Sub
End Class
或者可以动态加载一个类并继承它?
'This class has the some of the properties/methods/etc as the library being imported
Public Class MyProject.SomeClassWrapper
Inherits System.Windows.Forms.AxHost
Public Sub New(clsid As String)
MyBase.New(clsid)
End Sub
Public Sub SomeSubroutineHere()
'Do something
End Sub
End Class
'This class needs to inherit from a dynamically loaded assembly via reflection
Public Class MyClass
Inherits MyProject.SomeClassWrapper
Public Sub New()
Dim dynamicallyLoadedAssembly As System.Reflection.Assembly = System.Reflection.Assembly.LoadFile("C:\Temp\SomeLibrary.dll")
Dim newInstance = dynamicallyLoadedAssembly.CreateInstance("SomeLibrary.SomeClass")
Dim strCLSID as String = "Where can i get the CLSID from here?"
MyBase = newInstance '<<< I want to set "MyBase" to the new instance so that when MyBase.New() is called, it's the full inherited library
MyBase.New(strCLSID)
End Sub
End Class
提前致谢!
答案 0 :(得分:1)
不,你不能做这些事情。创建(或创建)对象后,它不能更改类型或实例。 VB是一种静态类型的语言。
但你可以使用装饰器模式来接近。
试试这个:
Public Interface IDecorator
Sub DoSomething()
End Interface
Public Class MyDecoratorClass
Implements IDecorator
Private _inner As IDecorator
Public Sub New()
Dim dynamicallyLoadedAssembly = System.Reflection.Assembly.LoadFile("C:\Temp\SomeLibrary.dll")
Dim newInstance = dynamicallyLoadedAssembly.CreateInstance("SomeLibrary.SomeClass")
_inner = CType(newInstance, IDecorator) ' `newInstance` must implement `IDecorator`
End Sub
Public Sub DoSomething() Implements IDecorator.DoSomething
_inner.DoSomething()
End Sub
End Class
现在,当您在IDecorator
上调用MyDecoratorClass
方法时,实际调用将通过动态加载的实例发送。