注意:这个问题不是询问如何传递类的实例。它询问如何传递具有共享项的类。
例如...... 关于如何制作能够做到这一点的功能的任何想法?
Public Function InsertSQL(ByVal xClass As Type) As String
InsertSQL = "Insert into "
InsertSQL = InsertSQL & xClass.TableName
InsertSQL = InsertSQL & " ("
InsertSQL = InsertSQL & xClass.FieldList
InsertSQL = InsertSQL & " )"
End Function
使用这样的一组类:
Public Class cClient
Public Shared TableName = "Clients"
Public Shared Function FieldList() As String
FieldList = "Name, Phone"
End Function
End Class
Public Class cSale
Public Shared TableName = "Sales"
Public Shared Function FieldList() As String
FieldList = "Name, Amount"
End Function
End Class
我在Google上搜索了“如何将一个类作为参数传递”,但是没有找到任何解决方法来访问该类的共享方法。我只能得到认为我想传递该类实例的结果。
请注意,此代码只是一个示例。 而且 - 当然,如果我传递一个类的实例,我没有问题 但是 - 这不是我想弄清楚的。
答案 0 :(得分:2)
我会在你的情况下使用Inheritance。 像这样的东西
Public Sub Main
Dim c = new cClient()
Dim sql = InsertSQL(c)
Console.WriteLine(sql)
End Sub
' Pass an actual instance of a class that inehrits cTableBase'
' all of these classes have the same BASE functions and property
' defined in the base class
Public Function InsertSQL(ByVal xClass As cTableBase) As String
InsertSQL = "Insert into "
InsertSQL = InsertSQL & xClass.TableName
InsertSQL = InsertSQL & " ("
InsertSQL = InsertSQL & xClass.FieldList
InsertSQL = InsertSQL & " )"
End Function
Public Class cTableBase
Public TableName As String
Public Overridable Function FieldList() As String
End Function
End Class
Public Class cClient
Inherits cTableBase
Public Sub New
TableName = "Clients"
End Sub
Public Overrides Function FieldList() As String
FieldList = "Name, Phone"
End Function
End Class
Public Class cSale
Inherits cTableBase
Public Sub New
TableName = "Sales"
End Sub
Public Overrides Function FieldList() As String
FieldList = "Name, Amount"
End Function
End Class
正如您在下面的评论中发表的那样。这可以使用传递给InsertSQL的方法使用反射
来完成Sub Main
Dim c = new cClient()
Dim result = InsertSQL(c.GetType())
Console.WriteLine(result)
End Sub
Public Function InsertSQL(ByVal xClass As Type) As String
Dim fi = xClass.GetField("TableName")
Dim tableName = fi.GetValue(xClass)
Dim mi = xClass.GetMethod("FieldList")
Dim fieldList = mi.Invoke(xClass, Nothing)
InsertSQL = "Insert into "
InsertSQL = InsertSQL & tableName
InsertSQL = InsertSQL & " ("
InsertSQL = InsertSQL & fieldList
InsertSQL = InsertSQL & " )"
End Function