c# - 使用验证覆盖列表中的 .Add 方法

标签 c# .net

我有一个用例,我想验证对象列表中的特定属性以确保它是唯一的。基本设置可以在下面的代码中看到。

class Program 
{
    static void Main(string[] args) 
    {
        Directory myDirectory = new Directory("Interaction Design");
        myDirectory.Books.Add(new Book("978-0-262-64037-4", "The Design of Everyday Things")); //Should be added
        myDirectory.Books.Add(new Book("978-0-262-13474-3", "Designing Interactions")); //Should be added
        myDirectory.Books.Add(new Book("978-0-262-13474-3", "Whoops, I slipped up")); //Should NOT be added
    }
}

public class Directory 
{
    public Directory(string name) 
    {
        Name = name;
    }
    public string Name { get; set; }
    public List<Book> Books { get; set; } = new List<Book>();
}

public class Book 
{
    public Book(string isbn, string title) 
    {
        Isbn = isbn;
        Title = title;
    }
    public string Title { get; set; }
    public string Isbn { get; set; }
}

现在,在上面的代码中,如果 ISBN 编号不唯一,则在图书列表中添加一本新图书应该会引发异常。

我想扩展 List 的 .Add() 方法并添加该验证,但我不确定如何真正做到这一点。

我见过类似的事情,但他们都假设 Directory 继承自 List 并且您编写了一个重写的 .Add 方法到 Directory - 在这种情况下这看起来不像是有效的解决方案。

也许我的一般方法是倒退的?

请指教。

最佳答案

如果您想要唯一性,请使用能满足您要求的集合:集合

制作一个IEqualityComparer<book>如果 Isbn 匹配并在 HashSet<Book> 中使用它,则认为两本书是相同的代表您独特的图书列表:

public class Directory 
{

    public HashSet<Book> Books { get; } 
        = new HashSet<Book>(new BookEqualityComparer());
    //...
    private class BookEqualityComparer : IEqualityComparer<Book>
    {
        public bool Equals(Book x, Book y)
        {
            if (ReferenceEquals(x, y))
                return true;

            if (ReferenceEquals(x, null) ||
                ReferenceEquals(y, null))
                return false;

            return x.Isbn == y.Isbn;
        }

        public int GetHashCode(Book obj)
            => obj.Isbn.GetHashCode();
    }
}

大功告成,Books 中不能有任何重复的书籍.

关于c# - 使用验证覆盖列表中的 .Add 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47705286/

相关文章:

c# - XPath normalize-space() 不能作为阶梯函数工作?

c# - 在 gridview (C#) 中获取 SQLite 数据不起作用

c# - Visual Studio Code 中的 XML 自动注释 C#

c# - 如何在 C# Windows 应用商店应用程序(也称为 WinRT/Metro)中创建查询字符串?

c# - 将 WSDL 导入 .NET 项目只会创建一个空的命名空间

.net - 为非常量类型的属性设置默认值?

c# - 可空对象必须有值错误

c# - .NET WebSocket 客户端和服务器库

c# - 棘手的 Entity Framework 一对一关系

.net - 在 .NET 应用程序中生成和打印发票的最佳方式是什么?