【发布时间】:2018-12-24 15:29:58
【问题描述】:
我有一个名为“PartTypes”的类,其中包含一个“PartType”对象的共享列表。我在 PartTypes 类中有一个“Item”属性,它按名称检索共享列表中的 PartType。
在我的主要代码中,我希望能够说类似PartTypes("ItemX") 而不是PartTypes.Item("ItemX")。但是,我不知道如何使共享的“项目”属性也成为我班级的默认属性。
这是我想要做的一个简化和浓缩的版本,使用 String 列表而不是 PartType 列表:
Sub MainCode
'How I have to do it now:
oPartType = PartTypes.Item("Type1")
'How I'd like to do it:
oPartType = PartTypes("Type1")
End Sub
Class PartTypes
Private Shared _PartTypes As New List(Of String)
'Initialize global list of PartTypes:
Shared Sub New
_PartTypes.Add("Type1")
_PartTypes.Add("Type2")
End Sub
'Property I want to be the "default":
Public Shared ReadOnly Property Item(Name As String) As String
Get
If _PartTypes.Contains(Name) Then
Return Name
Else
Return ""
End If
End Get
End Property
End Class
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~
如果您想知道我为什么要这样做,这里有一个扩展版本,应该可以更好地了解我实际上是如何使用 PartTypes 类的(但您不需要消化所有除非您愿意,否则适用于上述简化版本的解决方案可能适用于实际情况):
Function SetUpType(TestTypeName As String) As PartType
If PartTypes.IsType(TestTypeName) Then
Dim oPartType As PartType
'How I have to get the PartType object:
oPartType = PartTypes.Item(TestTypeName)
'How I'd like to get the PartType object:
'oPartType = PartTypes(TestTypeName)
'Set up oPartType:
'...
Return oPartType
Else
Return New PartType
End If
End Function
Class PartType
Public Name As String
Public [Class] As String
'Other properties of a PartType:
'...
End Class
Class PartTypes
Private Shared _PartTypes As New List(Of PartType)
'Initialize global list of PartTypes:
Shared Sub New
Add("Type1","ClassA")
Add("Type2","ClassA")
Add("Type3","ClassB")
Add("Type4","ClassC")
End Sub
Private Shared Function Add(Name As String, [Class] As String) As PartType
Dim oPartType As New PartType
oPartType.Name = Name
oPartType.Class = [Class]
_PartTypes.Add(oPartType)
Return oPartType
End Function
'Property I want to be the "default":
Public Shared ReadOnly Property Item(Name As String) As PartType
Get
For Each oPartType As PartType In _PartTypes
If oPartType.Name = Name Then Return oPartType
Next
'If Type not found...
Return New PartType
End Get
End Property
'Examples of other PartTypes functions:
Public Shared Function IsType([TypeName] As String) As Boolean
For Each oPartType As PartType In _PartTypes
If oPartType.Name = [TypeName] Then Return True
Next
'If Type not found...
Return False
End Function
End Class
【问题讨论】:
-
我很困惑,当您使用 Item 属性时,您正在返回一个字符串,而当您只想使用类的名称时,您正在返回一个 PartType 的实例。我在这里错过了什么吗?
-
在查看了扩展版本之后,我认为您应该为您的构造函数使用重载并将设置名称的逻辑放在那里。但你最终会调用 New PartTypes("Type1")。
标签: vb.net class default shared