是否有一个基类,我应该继承,这只是一个基本的名称/值对?我可以继承的名称/值类?
例如,我有几个只有两个属性(名称和值)的类。他们都称为独特的喜欢的字段,数据等等,都用于不同的东西,但内脏是相同的,两个属性(名称和值),他们有一个相关的集合类继承自CollectionBase。有什么我可以做的,所以他们都共享相同的代码或从相同的基类继承,所以它不是多余的?它们也位于组件的不同保护级别,所以我不想只为每种情况使用相同的类。
Public Class Field
Public Sub New()
End Sub
Private _name As String
Public Property Name() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
Private _value As String
Public Property Value() As String
Get
Return _value
End Get
Set(ByVal value As String)
_value = value
End Set
End Property
End Class
Private NotInheritable Class FieldCollection
Inherits CollectionBase
Public Sub New()
End Sub
Public Sub Add(ByVal field As Field)
List.Add(field)
End Sub
Public Sub Remove(ByVal index As Integer)
If index > Count - 1 Or index < 0 Then
Console.WriteLine("Can't remove this item")
Else
List.RemoveAt(index)
End If
End Sub
Default Public ReadOnly Property Item(ByVal index As Integer) As Field
Get
Return CType(List.Item(index), Field)
End Get
End Property
End Class
Public Class Data
Public Sub New()
End Sub
Private _name As String
Public Property Name() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
Private _value As String
Public Property Value() As String
Get
Return _value
End Get
Set(ByVal value As String)
_value = value
End Set
End Property
End Class
Private NotInheritable Class DataCollection
Inherits CollectionBase
Public Sub New()
End Sub
Public Sub Add(ByVal data As Data)
List.Add(data)
End Sub
Public Sub Remove(ByVal index As Integer)
If index > Count - 1 Or index < 0 Then
Console.WriteLine("Can't remove this item")
Else
List.RemoveAt(index)
End If
End Sub
Default Public ReadOnly Property Item(ByVal index As Integer) As Data
Get
Return CType(List.Item(index), Data)
End Get
End Property
End Class
等等
UPDATE
Here's a PasteBin of the code that I'm looking to streamline.希望这有助于。
这似乎是足够的,但OP指出他不想使用相同的类,而'KeyValuePair'是'struct',所以继承不是一个选项。 –
我想写一个继承Tuple的类,但是我无法使它工作。它只是告诉我Tuple 不包含带0参数的构造函数。尽管我写了一个构造函数,它带有2个参数,一个Enum和一个字符串。 –
Nick
@Nick错误并不是抱怨你的继承类,而是关于元组。由于Tuple没有0参数构造函数,所以你必须自己调用其中一个可用的构造函数。例如。 public MyClass(Enum myEnum,string str):base(myEnum,str){}。虽然我不确定你为什么从Tuple继承,而不是仅仅使用它或结构。 –