【问题标题】:How to resolve an InvalidOperationException on Bool condition?如何解决布尔条件下的 InvalidOperationException?
【发布时间】:2016-04-10 19:50:24
【问题描述】:

我已经设置了一个 bool 属性来防止或允许根据该 bool 设置为 true 触发命令。

在当前的实现中,在将 bool 设置为 true 之前,我会在 bool 中检查某些值是否不为空。

问题:

为什么我在 bool 内的条件下得到 InvalidOperationException?

代码概览:

布尔属性CanSendCommand,在下面的Relay命令中用作参数:

private bool CanSendCommand()
{
    if (SelectedParkDuration.Value != null && RegNumber != string.Empty && SelectedZone.ZoneName != null)
    {
        return true;
    }

    return false;
}

TagRequestCommand 最初在类初始化的加载方法中调用。命令本身绑定到 UI 上的按钮按下。

对于上下文 RegNumber 是字符串类型,SelectedParkingDuration 是 ?TimeSpan,SelectedZone.ZoneName 是属性中的字符串:

    private void LoadCommands()
    {
        TagRequestCommand = new RelayCommand(async () =>
        {
            await SendParkingTagSMSRequest();
        } ,CanSendCommand );
    }

我已经复制了异常详细信息,它告诉我条件的值为 null 应该没问题,因为它在 bool 条件中处理。然后我看到有一条线指向“可空对象必须有一个值”,这告诉我也许我的 Timespan 属性 SelectedParkDuration 应该有一个值。但我不确定在选择值之前它如何具有值。

System.InvalidOperationException was unhandled by user code
  HResult=-2146233079
  Message=Nullable object must have a value.
  Source=mscorlib
  StackTrace:
       at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
       at System.Nullable`1.get_Value()
       at Parking_Tag_Picker_WRT.ViewModel.TagRequestViewModel.CanSendCommand()
  InnerException: 

运行时自动窗口的屏幕截图:

【问题讨论】:

    标签: c# windows-phone-8.1 boolean-logic invalidoperationexception relaycommand


    【解决方案1】:

    Linqpad 中的简单代码可重现您建议的场景:

    void Main()
    {
        // Test.SelectedParkDuration = 5;
    
        var result = Test.SelectedParkDuration.Value; // Invalid operation exception with above line commented out
    
        result.Dump();
    }
    
    public class Test
    {
        public static int? SelectedParkDuration { get; set;}
    }
    

    如果您希望Test.SelectedParkDuration.Value; 成功,则首先分配,否则将是Null Reference exception,.Net 更喜欢Invalid Operation Exception 建议使用不正确,否则如果您期望值为 Null 则不应使用Value property

    要使上述代码正常工作,请注释掉该行:

    // Test.SelectedParkDuration = 5;
    

    也检查一下link

    【讨论】:

      【解决方案2】:

      看起来SelectedParkDuration.Value != null 是引发异常的部分。您可以简单地检查SelectedParkDuration != null

      更多信息:https://msdn.microsoft.com/en-us/library/ydkbatt6(v=vs.110).aspx

      【讨论】:

        猜你喜欢
        • 2021-03-18
        • 1970-01-01
        • 2017-01-10
        • 2013-08-16
        • 1970-01-01
        • 1970-01-01
        • 2013-09-23
        • 2020-02-07
        • 2016-05-11
        相关资源
        最近更新 更多