以下类在 ASP.NET 应用程序中用于从数据库结果集中读取货币并将它们相加(例如以美元显示总计加上以 GB 磅显示总计)。它以下列方式工作:
- 读取货币 ID 值
- 如果货币 ID 已存在,则增加该货币的总数
- 如果货币 ID 不存在,则将其与其值一起添加到列表中
- 下一个
使用该CurrencyID
属性作为每种独特货币之间的区别,效果很好。但是,现在很明显,IsoCurrencySymbol
默认情况下每种货币也是唯一的,因此CurrencyID
实际上并不需要。
所以...我想知道是否可以从此类继承并删除对 的任何引用CurrencyID
,因此改为CompareTo
使用该方法IsoCurrencySymbol
。
诀窍是保留现有的类,因为它被广泛使用,但引入一个不需要的修改版本CurrencyID
。请问这样可以吗?
<Serializable()> _
Public Class CurrencyCounter
<Serializable()> _
Private Class CurrencyType
Implements IComparable
Public IsoCurrencySymbol As String
Public CurrencySymbol As String
Public CurrencyID As Int16
Public Amount As Decimal
Public Function CompareTo(obj As Object) As Integer Implements System.IComparable.CompareTo
If Not TypeOf (obj) Is CurrencyType Then
Throw New ArgumentException("Object is not a currency type")
Else
Dim c2 As CurrencyType = CType(obj, CurrencyType)
Return Me.CurrencyID.CompareTo(c2.CurrencyID)
End If
End Function
End Class
Private _Currencies As List(Of CurrencyType)
Public Sub New()
_Currencies = New List(Of CurrencyType)
End Sub
Private Sub AddStructToList(CurrencyID As Integer, IsoCurrencySymbol As String, CurrencySymbol As String, Amount As Decimal)
If IsoCurrencySymbol <> String.Empty AndAlso Amount > 0 Then
Dim s As New CurrencyType
s.CurrencyID = CurrencyID
s.IsoCurrencySymbol = IsoCurrencySymbol
s.CurrencySymbol = CurrencySymbol
s.Amount = Amount
_Currencies.Add(s)
End If
End Sub
Public Sub Add(CurrencyID As Integer, IsoCurrencySymbol As String, CurrencySymbol As String, Amount As Decimal)
Dim ct As CurrencyType = _Currencies.Find(Function(obj) obj.CurrencyID = CurrencyID)
If ct IsNot Nothing Then
ct.Amount += Amount
Else
AddStructToList(CurrencyID, IsoCurrencySymbol, CurrencySymbol, Amount)
End If
End Sub
Public Sub Clear()
_Currencies.Clear()
End Sub
Public Function Count() As Integer
Return _Currencies.Count
End Function
Public Function RenderTotals() As String
' ...
End Function
End Class