我似乎得到了一个无法解释的System.InvalidOperationException,指出当我检查对象的值是否为null时,“可为null的对象必须具有值”。不幸的是,我只随机收到每1,000,000条消息中的1条,并且似乎无法在本地环境中使用模拟器进行复制,这就是为什么我向你们寻求帮助。
我有一个foreach循环,用于处理对象数组:
ReceivedMessage[] messages = pushFeed.ReceivedMessages.GetOustandingMessages();
foreach (var m in messages)
{
if (m != null) // only here as a sanity check to ensure m was not somehow null
{
if(pushFeed.Feed.ForwardReceivedMessage(m))
logger.Info("Successfully posted to server");
else
logger.Warn("Failed to post to server");
}
}
在ForwardReceivedMessage
内部,然后检查消息对象中的Source
对象是否为null,这就是我似乎正在获取InvalidOperationException的地方。
public bool ForwardReceivedMessage(ReceivedMessage message)
{
CommToken token;
if (message.Source == null) // This is the line where the exception is being thrown...?
{
logger.Warn("Failed to forward feed with null Source...");
return false;
}
// Do other things...
return true;
}
ReceivedMessage
对象很简单:
public class ReceivedMessage
{
public long MessageId;
public MessageBase Payload;
public IAsset Source;
}
Source
对象只是具有以下内容的接口:
public interface IAsset
{
int ClientId { get; }
ushort CommId { get; }
int DeviceId { get; }
short DeviceMode { get; set; }
DateTime? LastReportTime { get; }
string Name { get; }
bool? Panic { get; }
int? PassthroughDeviceId { get; set; }
DeliveryMethod PrimaryMTDeliveryMethod { get; }
DeliveryMethod? SecondaryMTDeliveryMethod { get; }
// ... etc, etc
}
据我所知,唯一的问题可能是Source
对象,并且简单地调用message.Source
来检查它是否为null似乎是引发InvalidOperationException的原因。
我认为这可能与将Source
声明为接口IAsset
(而不是对象)有关,但是即使从未分配Source
,我相信我也会能够检查if语句中是否有值?
我希望这里的人可以解释这种情况的发生方式/原因,并提供一种解决方法,可以检查Source
是否有价值。
编辑: 我得到的完整异常打印输出是:
System.InvalidOperationException: Nullable object must have a value.
at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
at CompanyName.Division.MessageHandler.Platform.PlatformHandler.ForwardReceivedMessage(ReceivedMessage message) in c:\Git\message-handler\MessageHandler\PlatformFeeds\CompanyName.Division.MessageHandler.Platform\PlatformHandler.cs:line 37
at CompanyName.Division.MessageHandler.Core.FeedManager.<SendCallback>d__11.MoveNext() in c:\Git\message-handler\MessageHandler\CompanyName.Division.MessageHandler.Core\FeedManager.cs:line 160