【发布时间】:2011-06-04 09:42:18
【问题描述】:
我已经看到其他一些关于此的回复,他们谈论接口,但我很确定您可以使用类和基类来做到这一点,但我不能这样做。
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) 返回的任何内容转换为 Behavior 类型的基类时,我得到了无效的强制转换异常。该类型应该是 CharacterController ,它被定义为 Behavior 的子级,那么为什么不让我转换它呢?我以前做过类似的事情,但我找不到我的代码。我错过了什么?
【问题讨论】:
-
也许用
DirectCast(Activator.CreateInstance(t), Behavior) -
是的,我都试过了,但还是不行。 ://
-
也许你应该检查返回的对象的类型,看看它到底是什么。
-
它说 CharacterController.CharacterController。它说它的基本类型是 Behavior.Behavior。这就是让我困惑的地方。此外,如果我专门引入 CharacterController 的引用并创建它的一个对象,那么一切正常。所以我一定是错过了什么。
标签: vb.net reflection dynamic