检查接口中的对象是否具有值时,发生InvalidOperationException

时间:2018-07-16 11:26:39

标签: c# .net interface

我似乎得到了一个无法解释的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

0 个答案:

没有答案