C# 未引发list.removeall参数null异常
我有一个struct类型的列表,当数据写入数据库或文件时,我会在其中临时添加数据并将其删除。我正在使用C# 未引发list.removeall参数null异常,c#,C#,我有一个struct类型的列表,当数据写入数据库或文件时,我会在其中临时添加数据并将其删除。我正在使用list.RemoveAll方法从列表中删除项 如果我在计数为零的列表上调用它,但即使计数为零,它也不会引发任何异常,list.RemoveAll应该引发ArgumentNullException _dataNotWrittenToDb.RemoveAll(item => item.ScopeId == _a2Data.ScopeId); _dataWrittenToDB.
list.RemoveAll
方法从列表中删除项
如果我在计数为零的列表上调用它,但即使计数为零,它也不会引发任何异常,list.RemoveAll
应该引发ArgumentNullException
_dataNotWrittenToDb.RemoveAll(item => item.ScopeId == _a2Data.ScopeId);
_dataWrittenToDB.RemoveAll(item => item.ScopeId == _a2Data.ScopeId);
如果
count
为0,则表示列表为空。但名单是存在的Null
表示列表不存在
NullReferenceException
将仅在null
对象上抛出,而不是清空
与根本没有盒子相比,它就像现实生活中的一个空盒子
例外情况
Exception Condition
ArgumentNullException
match is null.
RemoveAll仅当传递的参数为null时才会抛出ArgumentNullException,在您的情况下,它不是null
RemoveAll的工作是删除与给定条件匹配的所有元素,在您的情况下,没有匹配的元素,没有删除,也没有理由从列表反编译源返回异常:
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;
}
public int RemoveAll(谓词匹配)
{
if(match==null)
ThrowHelper.ThrowArgumentNullException(argument.match除外);
int index1=0;
而(index1=该尺寸)
返回0;
int index2=index1+1;
而(index2<此尺寸)
{
而(index2
正如您所看到的,此方法引发
ArgumentNullException
的唯一时间是参数实际等于null
如果需要异常,可以执行以下操作:
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);
谓词p=item=>item.ScopeId==\u a2Data.ScopeId;
如果(!_datanotwritentodb.存在(p))
抛出新异常(“不存在要删除的项”);
_datanotwritentodb.RemoveAll(p);
如果(!_datawritentodb.存在(p))
抛出新异常(“不存在要删除的项”);
_datawritentodb.RemoveAll(p);
list.RemoveAll应该抛出ArgumentNullException,如果我在一个计数为零的列表上调用它-它在中说了什么?如果您编写了\u datanotwritentodb.RemoveAll(null)
,它会给您ArgumentNullException
。也许这就是你误解的地方。@JeppeStigNielsen我现在明白了,谢谢这与空列表与列表引用为null
无关ArgumentNullException
仅在参数为null
时抛出,而不是在列表本身为null
时抛出(在这种情况下,抛出的是NullReferenceException
,而是由CLR而不是由类本身抛出)。此外,OP甚至没有提到NullReferenceException
,他在问关于异常的问题。是的,我错了。我认为这是IList的一种扩展方法。但这是一个具体的列表方法。如果是扩展方法,则调用扩展方法的变量将作为参数传递。这让我猜错了。啊,对,如果是那样的话,我的猜测应该是对的;我认为OP使用了列表
。