我正在尝试编写自己的收藏.当然,它包含通用值.当我试图检查array _content的值是否为null时 - 它运行良好,但仅当用户不使用整数时.
if (_content[_size - 1] != null)
Run Code Online (Sandbox Code Playgroud)
关键是用户可以创建整数集合,而数组会将所有值初始化为0.因此,当我尝试检查值是否为0时 - 它不会编译.
if (_content[_size - 1] != 0)
Run Code Online (Sandbox Code Playgroud)
具体不起作用此方法(如果集合由整数组成):
public void Add(T item)
{
if (_content[_size - 1] != null)
throw new ArgumentOutOfRangeException("The Array is full");
if (_size > 0)
{
for (int i = 0; i <= _size; i++)
{
if (_content[i] == null)
{
_content[i] = item;
break;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
你想要做的是一个坏习惯,所以不要这样做.
您的方法保留一个值,即零,表示"无".但是,零和零之间存在差异,因此当零是合法值时,您的方法会导致错误.
考虑当您的集合的用户为最后一个数字添加零时会发生什么.您的代码会认为单元格是空的,而不是应该抛出异常.
更好的方法是存储在_size字段中集合中设置的实际元素数.最后一个元素_content位于_content.Length-1,因此您的检查可以按如下方式进行:
if (_content.Length == _size) {
// InvalidOperationException is more appropriate here,
// because the error is caused by the state of your collection,
// rather than any particular argument passed to the method.
throw new InvalidOperationException("The Array is full");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
146 次 |
| 最近记录: |