Nullable和bool有什么区别

本文关键字:bool 什么 区别 Nullable | 更新日期: 2023-09-27 18:25:55

当我对我的类进行逆向工程时,我得到以下结果:

public Nullable<bool> Correct  { get; set; }
public Nullable<bool> Response { get; set; }

我编码:

public bool? Correct  { get; set; }
public bool? Response { get; set; }

有人可以告诉我这两者之间是否有任何区别。我以前没有见过Nullable<bool>,我不确定为什么它不只是创建一个"布尔

"。

注意:我已将编码更改为布尔? 以回应乔恩的评论

Nullable<bool>和bool有什么区别

"可以为 Nullable 赋值 true false 或 null。在处理包含可能未赋值的元素的数据库和其他数据类型时,将 null 赋值给数值和布尔类型的功能特别有用。例如,数据库中的布尔字段可以存储值 true 或 false,或者它可能未定义。

可为空的类型

有人可以告诉我这两者之间是否有任何区别。我 以前没有见过可为空的,我不确定为什么会这样 不只是创建一个"布尔">

从技术上讲,可为空和布尔值没有区别?。无论你写什么,它们都会在IL中编译为Nullable。所以没有区别。 这?只是 C# 编译器语法。

为什么需要可为空的系统

这是因为它被用作type。并且类型需要在namespace中.

但是布尔值和布尔值有区别?由于 bool 是一个简单的值类型,不能分配 null 值,而您可以将值分配给 bool?。

Nullable表示可以分配 null 的value type,它位于命名空间System 中。

此外,由于它可以被分配为null,因此您可以像这样检查它是否有值

if(Correct.HasValue)
{
  //do some work
}

Nullable<bool>bool?是等价的("?"后缀是句法糖(。 Nullable<bool>意味着除了典型的bool值:真和假,还有第三个值:null

http://msdn.microsoft.com/en-US/library/1T3Y8S4S(v=vs.80(.aspx http://msdn.microsoft.com/en-us/library/2cf62fcy.aspx

如果您使用不确定的值,空值可能会很有用,例如在某些您无法判断实例是否正确的情况(如果有响应(已经给出;例如,在您的案例中

  // true  - instance is correct
  // false - instance is incorrect
  // null  - additional info required
  public bool? Correct { get; set; }
  // true  - response was given 
  // false - no response
  // null  - say, the response is in the process
  public bool? Response { get; set; }

是的,Nullable<bool>bool之间是有区别的。

public Nullable<bool> Correct { get; set; } // can assign both true/false and null
Correct = null;  //possible 

在你的情况下,你不能拥有它

public bool Correct { get; set; } //can assign only true/false
Correct = null;  //not possible

也许之前编码的人可能不会接触到bool?数据类型。

System.Nullable<bool>等同于bool?

更新:Nullable<bool>bool?之间没有区别

没有区别。

提示:Nullable<Nullable<bool>> n; // not allowed

源 msdn 可为空的类型