Nullable object must have a value?

后端 未结 8 2364
旧时难觅i
旧时难觅i 2020-12-09 14:54

On the line: bool travel = fill.travel.Value; I am getting the following error:

Nullable object must have a value

a

相关标签:
8条回答
  • 2020-12-09 14:58

    You can always switch to

     fill.travel.GetValueOrDefault()
    

    To provide the default (false), or the value of the boolean column from the database. Or you can specify the default with an overload. Either way, the nullable currently doesnt have a value, which is why you get that exception.

    0 讨论(0)
  • 2020-12-09 14:58

    The value coming from the database is a nullable boolean. When you call Nullable.Value, and the value is null, you will get this exception. Consider checking the property Nullable.HasValue before calling .Value.

    0 讨论(0)
  • 2020-12-09 15:01

    Null is not false. See Eric Lippert's blog article series about this at: http://blogs.msdn.com/b/ericlippert/archive/2012/03/26/null-is-not-false.aspx

    You need to process a null result into a false, if that is how you want to translate it.

    To make this case clear, consider this code:

    bool travel;
    bool? temptravel = fill.travel.Value;
    if( temptravel == true )
        travel = true;
    else
        travel = false;
    

    Or just use Val Bakhtin's solution if you are using .Net 4

    0 讨论(0)
  • 2020-12-09 15:03

    You will get a InvalidOperationException if you access the Nullable.Value property when the HasValue property is false.

    0 讨论(0)
  • 2020-12-09 15:09

    You can always use the classic C ? operator like this:

    bool travel = (fill.travel == null ? false : fill.travel.Value);
    
    0 讨论(0)
  • 2020-12-09 15:11

    You are trying to access property from the nonexistent object (your fill.travel is null, and you calling prop from it), you can use coalesce operator (.Net 4.0):

    bool travel = fill.travel ?? false;
    
    0 讨论(0)
提交回复
热议问题