[英]Foreach System.NullReferenceException: Object reference not set to an instance of an object
I get System.NullReferenceException: Object reference not set to an instance of an object in this: 我得到System.NullReferenceException:对象引用未设置为此对象的实例:
var offeredItems = new List<ulong>(Trade.steamMyOfferedItems);
foreach (var item in offeredItems) {
Trade.RemoveItem(item);
}
What is different than in all such questions is that the exception is in line 3 from this code block. 与所有这些问题的不同之处在于,此代码块中的异常位于第3行。 Does it mean that Trade is null?
这是否意味着贸易是空的? That would be strange because I make this check a few operations earlier:
这很奇怪,因为我先检查了几个操作:
if (Trade != null && Trade.OtherSID == OtherSID) {
OnTradeMessage(message);
return;
}
The only reason for this would be if Trade was nulled in another thread (and that would be very unecxpected behaviour) in time of 5-10 simple operations, this would be really very strange. 唯一的原因是,如果Trade在5-10个简单操作的时间内被另一个线程(并且这将是非常不可思议的行为)所取代,这将是非常奇怪的。
EDIT: 编辑:
The problem is I can't reproduce this doing the exact same steps. 问题是我无法重现这一步做同样的步骤。 I guess Trade has to be null and it has to be nulled in other thread, there is no other option.
我猜贸易必须为空,并且必须在其他线程中为空,没有其他选择。 Sorry for stupid question.
抱歉愚蠢的问题。
EDIT2: EDIT2:
If Trade.RemoveItem
is executed, then offeredItems
is not empty, hence Trade
cannot be null
. 如果执行
Trade.RemoveItem
,则offeredItems
不为空,因此Trade
不能为null
。 In both cases offeredItems
should contain 1-2 elements. 在两种情况下,
offeredItems
应包含1-2个元素。 So as far as I know (and understand): 据我所知(并了解):
Trade
is not null
, Trade
is an object of class Trade
, which has method RemoveItem
(the exception is thrown exactly at this line: Trade.RemoveItem(item);
, not in RemoveItem
, RemoveItem
is not null
delegate (this code works most of the time) Trade
是不null
, Trade
是类的一个对象Trade
,其中有方法RemoveItem
(例外是在这一行正是抛出: Trade.RemoveItem(item);
,而不是在RemoveItem
, RemoveItem
是不是null
的委托(此代码的工作的最时间)
the exception is in line 3 from this code block
该代码块的第3行是异常
Does it mean that Trade is null?
这是否意味着贸易是空的?
It could mean that. 这可能意味着。 It sounds like one of the following possibilities:
这听起来像是以下可能性之一:
Trade
is null
. Trade
null
。 Trade
is a property whose getter throws a NullReferenceException
. Trade
是一个getter抛出NullReferenceException
的属性。 RemoveItem
is a null
delegate. RemoveItem
是一个null
委托。 RemoveItem
throws a NullReferenceException
. RemoveItem
抛出NullReferenceException
。 Why don't you step through the code in a debugger and find out? 为什么不在调试器中单步执行代码并查找? Also, please see the comments to your question.
另外,请查看您问题的评论。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.