从Inherited类返回Class对象

时间:2014-02-22 21:38:13

标签: vb.net inheritance reflection

我正在努力教自己反思并一直在谷歌搜索,但我无法完全绕过它。我创建了一个名为DataClass的类,它包含一个名为GetClassFromDB的方法,如下所示,它将从多个类继承。

我尝试做的是让我的数据类读取objResults中定义的TableName属性。一旦我从objResults中提取了tablename,我就会在SQL数据库中查询数据集。一旦我有了数据集,我将创建一个继承此类的相同TYPE的新对象(将是不同类型)并从数据集中填充它。一旦我有了新填充的课程,我将把它返回使用。

我相信我已经有了大部分的正确方法(如果有更好的方法,请纠正我),但我真正的问题是这个。如何创建一个类的新类,该类从我在代码中获得的字符串名称或类型中派生该类。我希望objResults的所有可访问属性都可用。

Namespace MyApp
Public Class DataClass
    Private _TableName As String
    Private _Name As String

    Overridable ReadOnly Property TableName As String
        Get
            Return _TableName
        End Get
    End Property

    Public Overloads Function GetClassFromDB() As Object
        Try
            Dim BaseObject As New Object
            'Get the object name
            Dim objName As String = MyBase.GetType().Name

            'Gets the type thats calling this method
            Dim objDerived As Type = MyBase.GetType()

            'Get the property info to request the tablename from the derived class
            Dim TableName As PropertyInfo = objDerived.GetProperty("TableName")
            Dim TableNameString As String = TableName.GetValue(Me, Nothing).ToString

            'Once I get the table name from objResults I can perform the SQL
            Dim QueryResults as DataSet = SQLiteCLass.Query("Select * FROM TableNameString")

            'Once I get data from the SQL I want to create a new object of the type deriving this method.
            'In this example is objResults
            Dim NewObject as objDerived

            'Now I can fill my new object with the results and return it as an object

            'THIS IS MY QUESTION - How can I create a new object of the TYPE that I receive from Reflection
            Return False
        Catch ex As Exception
            Return False
        End Try
    End Function

End Class
End Namespace

这是一个继承我的数据类的示例类。

Public Class objResults
Inherits MyApp.DataClass

Private _GameID As Guid

Public Property GameID As Guid
    Get
        Return _GameID
    End Get
    Set(ByVal value As Guid)
        _GameID = value
    End Set
End Property

Public Overrides ReadOnly Property TableName As String
    Get
        Return "This is my tablename"
    End Get
End Property
End Class

这就是我在代码中使用它的方法。

Dim objResult as New objResults
Dim TodaysResult as objResultsCollection

TodaysResult = objResult.GetClassFromDB()

0 个答案:

没有答案