首页 > 解决方案 > 我们如何为 List 抛出异常在 C# 中使用接口和构造?

问题描述

我需要在存储类 City 内的公司名称(名称可以在当前城市中存在一次)的列表上调用 throw ArgumentException。如果我有一个名字列表,如何创建一个名字列表并抛出异常?

class City : ICity
{
    private List<string> _companyNames;
    internal City(string name)
    {
        this.Name = name;
        _companyNames = new List<string>();
    }
    public string Name
    {
         get;  
    }

    public ICompany AddCompany(string name)
    {

        if (string.IsNullOrEmpty(name))
        {
            throw new ArgumentNullException("invalid name");
        }

        //create a list and check if exist
        List<string> _companyNames = new List<string>() {name, name, name};
        //public bool Exists(Predicate<T> match);
        //Equals(name) or sequennceEqual
        if (!_companyNames.Equals(obj: name))
        {
            throw new ArgumentException("name already used");
        }


        return new Company(name, this);
    }
}

标签: c#listexceptionarraylistargumentexception

解决方案


不要使用 aList<string>进行唯一性检查。随着列表的增长,它的效率会降低。考虑使用 a HashSet<string>

class City
{
    private readonly HashSet<string> _companyNames = new HashSet<string>();

    public ICompany AddCompany(string name)
    {
        // check 'name' for null here ...
        // ...

        // 'Add' will return 'false' if the hashset already holds such a string
        if (!_companyNames.Add(name))
        {
            throw new ArgumentException("Such a company already exists in this city");
        }

        // ... your code
    }
}

推荐阅读