2012-09-04 58 views
0

我有一个类型的结构体列表,其中我暂时添加数据并在数据写入数据库或文件时删除它们,我使用list.RemoveAll方法从列表中删除项目。list.removeall参数null抛出异常没有抛出

list.RemoveAll应该抛出ArgumentNullException如果我在一个列表中调用它的计数为零,但它没有抛出任何异常,即使计数为零。

_dataNotWrittenToDb.RemoveAll(item => item.ScopeId == _a2Data.ScopeId); 
    _dataWrittenToDB.RemoveAll(item => item.ScopeId == _a2Data.ScopeId); 
+1

*的list.RemoveAll应该抛出ArgumentNullException如果我把它称为其计列表上零* - 它在哪里说,在[文档](http://msdn.microsoft.com/en-us/library/wdka673a.aspx)? –

+0

如果你写了'_dataNotWrittenToDb.RemoveAll(null)',它会给你'ArgumentNullException'。也许这就是你误解的内容。 –

+0

@JeppeStigNielsen我现在明白了,谢谢 –

回答

2

MSDN

例外

Exception Condition 
ArgumentNullException 

match is null. 

removeall过抛出ArgumentNullException只有当传递的参数为空,你的情况不是null

removeall过的任务是去除所有匹配的元素给定的条件,在你的情况下没有匹配的元素,没有删除,没有理由返回异常

-1

如果count为0,表示列表为空。但名单存在。 Null表示该列表不存在。

NullReferenceException将只抛出null对象,而不是空容器。

这就像现实生活中的空盒子,相比之下根本没有盒子。

+1

这与空列表无关,而列表引用是'null'。当*参数*为'null'时,不是当列表本身为null(在这种情况下抛出'NullReferenceException',而是由CLR抛出,而不是类本身)抛出'ArgumentNullException'。 –

+0

另外,OP甚至没有提及'NullReferenceException',他询问'ArgumentNullException'。 –

+0

是的,我错了。我虽然这是IList的扩展方法。但这是一个具体的列表方法。如果它是扩展方法,则调用扩展方法的变量将作为参数传递。这导致我错误的表现。 –

0

从列表反编译来源:

public int RemoveAll(Predicate<T> match) 
    { 
     if (match == null) 
     ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); 
     int index1 = 0; 
     while (index1 < this._size && !match(this._items[index1])) 
     ++index1; 
     if (index1 >= this._size) 
     return 0; 
     int index2 = index1 + 1; 
     while (index2 < this._size) 
     { 
     while (index2 < this._size && match(this._items[index2])) 
      ++index2; 
     if (index2 < this._size) 
      this._items[index1++] = this._items[index2++]; 
     } 
     Array.Clear((Array) this._items, index1, this._size - index1); 
     int num = this._size - index1; 
     this._size = index1; 
     ++this._version; 
     return num; 
    } 

正如你所看到的唯一的时候此方法抛出ArgumentNullException时的说法实际上是等于null

1

如果你想例外,你可以做这样的事情:

Predicate<YourItemStruct> p = item => item.ScopeId == _a2Data.ScopeId; 

if (!_dataNotWrittenToDb.Exists(p)) 
    throw new Exception("No items exist to delete"); 
_dataNotWrittenToDb.RemoveAll(p); 
if (!_dataWrittenToDb.Exists(p)) 
    throw new Exception("No items exist to delete"); 
_dataWrittenToDb.RemoveAll(p);