2

我的班级成员“用户名”对于创建的所有“卖家”必须是唯一的吗?我可以在课堂上实现它还是主要实现它?两个类成员也不能为空或包含空格。我是否应该将所有对象存储在列表中,然后验证所述用户名是否已经存在?我很困惑我应该把它放在哪里。

Public Class Seller

Private _username As String
Private _password As String

Public Sub New(aname As String, apassword As String)
    Me.Password = apassword
    Me.UserName = anom
End Sub

Public Property Username As String
    Get
        Return _username
    End Get
    Set(value As String)
        Dim test As String = value
        test.Replace(" ", "")
        test.Trim()
        If (test <> value Or value = " ") Then
            Throw (New ArgumentException("Username cannot be empty or contain spaces")  
        Else
            _username = value
        End If
    End Set
End Property

Public Property Password As String
    Get
        Return _password
    End Get
    Set(value As String)
        Dim test As String = value
        test.Replace(" ", "")
        test.Trim()
        If (test <> value Or value = " ") Then
            Throw (New ArgumentException("Password cannot be empty or contain spaces")  
        Else
            _password = value
        End If

    End Set
End Property
End Class

谢谢

4

2 回答 2

2

考虑一下面向对象设计对责任的看法,以及“需要知道”的原则。

  • 每个Seller对象都负责确保自己的唯一性吗?
  • Seller每个对象检查所有其他对象是否可以接受/合适Seller- 甚至知道它们存在?还是让这个对象只知道它自己的销售数据更有用?
于 2013-11-06T14:40:45.647 回答
1

HashSet<T>是您要查找的集合类型。

根据 MSDN:

HashSet 类提供高性能的集合操作。集合是不包含重复元素且其元素没有特定顺序的集合。

注意:HashSet<T>.Add()方法返回一个BooleanTrue如果该项目已添加到集合中并且False该项目已经存在)。

所以你的代码应该是这样的:

Dim theSellers As New HashSet(Of Seller)
Dim success As Boolean = theSellers.Add(New Seller())

' Was the addition of the Seller successful or not?     
If Not success Then
    ' No, so do something here for duplicates if you wish
End If
于 2013-11-06T14:35:41.940 回答