4

当我对我的课程进行逆向工程时,我得到以下信息:

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

我编码:

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

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

注意:我将编码更改为 bool?回应乔恩的评论

4

5 回答 5

5

“可以为 Nullable 分配值 true false 或 null。当您处理包含可能未分配值的元素的数据库和其他数据类型时,将 null 分配给数字和布尔类型的能力特别有用。例如,数据库中的布尔字段可以存储值真或假,或者它可能是未定义的。”

可空类型

于 2013-08-01T06:03:16.463 回答
5

有人可以告诉我这两者之间是否有任何区别。我以前没有见过 Nullable,我不知道为什么它不只是创建一个“布尔”

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

为什么需要 Nullable 系统

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

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

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

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

if(Correct.HasValue)
{
  //do some work
}
于 2013-08-01T06:15:45.300 回答
2

是的之间有区别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?dataType。

System.Nullable<bool>相当于bool?

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

于 2013-08-01T06:12:12.037 回答
2

Nullable<bool>并且bool?是等价的(“?”后缀是语法糖)。 Nullable<bool>意味着除了典型bool值:true 和 false,还有第三个值: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; }
于 2013-08-01T06:19:52.427 回答
1

没有区别。

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

源 msdn 可空类型

于 2013-08-01T06:18:40.397 回答