c# - 我们如何为 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);
}
}
解决方案
不要使用 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
}
}
推荐阅读
- javascript - 如何通过 __vue__ 访问循环项的对象?
- scala - scala:返回可变参数的方法
- python - /blog/ Django 2.0.5 中的 NoReverseMatch
- r - 运行 MethylMix R 包时出错
- python - 未检测到 DynamicRelationField
- cucumber - 我的第一个基本 Cucumber 程序(场景)失败 - Java
- javascript - 引导网格:减小窗口大小时,最后一个 div 不会出现在下一行
- python - pip install requests[security] 本身会引发 InsecurePlatform 警告/错误
- angularjs - 带有 html 不安全的 Uib 工具提示
- corda - 是否应该使用 Corda Workflow 来管理一般业务工作流