我已經看到了一些其他的迴應,他們談論的接口,但我敢肯定,你可以做到這一點的類和基類,但我不能這個工作。.net動態加載
Public Class Behavior
Private _name As String
Public ReadOnly Property Name As String
Get
Return _name
End Get
End Property
Public Property EditorUpdate As Boolean
Public Sub New(ByVal name As String)
_name = name
EditorUpdate = False
End Sub
Public Overridable Sub Update()
End Sub
' runs right away in editor mode. also runs when in stand alone game mode right away
Public Overridable Sub Start()
End Sub
' runs after game mode is done and right before back in editor mode
Public Overridable Sub Finish()
End Sub
' runs right when put into game mode
Public Overridable Sub Initialize()
End Sub
' runs when the game is complete in stand alone mode to clean up
Public Overridable Sub Destroy()
End Sub
末級
Public Class CharacterController
Inherits Behavior.Behavior
Public Sub New()
MyBase.New("Character Controller")
End Sub
Public Overrides Sub Update()
' TODO: call UpdateController()
' THINK: how can UpdateController() get the controller entity it's attached to?
' Behaviors need a way to get the entity they are attached to. Have that set when it's assigned in the ctor?
End Sub
末級
Dim plugins() As String
Dim asm As Assembly
plugins = Directory.GetFileSystemEntries(Path.Combine(Application.StartupPath, "Plugins"), "*.dll")
For i As Integer = 0 To plugins.Length - 1
asm = Assembly.LoadFrom(plugins(i))
For Each t As Type In asm.GetTypes
If t.IsPublic Then
If t.BaseType.Name = "Behavior" Then
behaviorTypes.Add(t.Name, t)
Dim b As Behavior.Behavior
b = CType(Activator.CreateInstance(t), Behavior.Behavior)
'Dim o As Object = Activator.CreateInstance(t)
End If
End If
Next
Next
當它試圖轉換任何Activator.CreateInstance(T)返回到基類類型的行爲我越來越無效拋出異常。該類型應該是CharacterController,它被定義爲Behavior的子元素,所以爲什麼它不讓我進行該操作?我之前做過這樣的事情,但是我找不到我的代碼。我錯過了什麼?
也許使用'DirectCast(Activator.CreateInstance(t),Behavior)' – IAbstract 2011-01-06 01:46:10
是的,我試了兩次,它仍然沒有工作。 :/ – user441521 2011-01-06 01:54:54
也許你應該檢查返回的對象的類型,看看它到底是什麼。 – cdhowie 2011-01-06 01:56:15