简体   繁体   English

我们如何为 List 抛出异常<string>在 C# 中使用接口和构造?

[英]How can we throw exception for List<string> in C# with used interfaces and constructs?

I need to call throw ArgumentException on the list which stores name of company (name can exist once in current city) inside of a class City.我需要在类 City 内存储公司名称(名称可以在当前城市中存在一次)的列表上调用 throw ArgumentException。 How can I create a list of names and throw the exception if I have a list of names?如果我有姓名列表,如何创建姓名列表并抛出异常?

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);
    }
}

Don't use a List<string> for uniqueness-checking.不要使用List<string>进行唯一性检查。 It will become less efficient as the list will grow.随着列表的增长,它的效率会降低。 Consider using a HashSet<string> for that.考虑为此使用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
    }
}

If you want the Add itself to throw the exception, one thing you could do is to create your own implementation.如果您希望 Add 本身抛出异常,您可以做的一件事是创建自己的实现。 Something like the following:类似于以下内容:

public class MyList<T> : List<T>
{
    public new void Add(T item)
    {
        if (Contains(item))
        {
            throw new ArgumentException("Item already exists");
        }
        base.Add(item);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM