【问题标题】:How can I make a class member unique for each instance created?如何使每个创建的实例的类成员唯一?
【发布时间】:2013-11-17 19:35:45
【问题描述】:

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

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

谢谢

【问题讨论】:

  • 一种方法是将它们存储在 List(Of Seller) 中,然后在创建之前扫描它以获取新名称

标签: vb.net class oop object


【解决方案1】:

HashSet&lt;T&gt; 是您要查找的集合类型。

每个 MSDN:

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

注意:HashSet&lt;T&gt;.Add() 方法返回 Boolean(如果项目已添加到集合中,则返回 True,如果项目已存在,则返回 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

【讨论】:

  • 谢谢,非常有帮助。遗憾的是,我不能使用 HashSets,因为任务是在不使用任何 Arrays 属性的情况下手动创建列表(我应该在问题中提到它),但这是有道理的,我还没有学会。
  • @user2960568 - 好的,我希望这对您以后有所帮助,如果您觉得答案有用,请随时对答案进行投票。 :-)
  • 很遗憾我不能投票,因为我缺乏“声誉”,但当我有足够的时候我会回来。
【解决方案2】:

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

  • 是否每个Seller 对象都负责确保其自身的唯一性?
  • 每个Seller 对象检查所有其他Seller 对象是否可以接受/合适——即使知道它们存在?还是让这个对象只知道自己的销售数据更有用?

【讨论】:

  • 感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2020-02-13
  • 1970-01-01
  • 2021-11-19
  • 1970-01-01
  • 1970-01-01
  • 2022-07-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多