C# "bool" 和 "bool" 和有什么不一样?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1181491/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's the difference between "bool" and "bool?"?
提问by Roee Adler
I use the "bool" type for variables as I was used to in C++, and I try to put the values of functions or properties I expect to be boolean into my variable. However I often encounter cases where the result type is "bool?" and not "bool" and the implicit casting fails.
我使用“bool”类型作为变量,就像我在 C++ 中习惯的那样,我尝试将我希望是布尔值的函数或属性的值放入我的变量中。但是我经常遇到结果类型为“bool”的情况?而不是“bool”并且隐式转换失败。
What is the difference between the two and when is each used? Also, should I use "bool?" as the type for my variable? Is this the best practice?
两者有什么区别,分别在什么时候使用?另外,我应该使用“bool”吗?作为我的变量的类型?这是最佳做法吗?
采纳答案by CMS
The ?
symbol after a type is only a shortcut to the Nullable type, bool?
is equivalent to Nullable<bool>
.
?
类型后面的符号只是Nullable 类型的快捷方式,bool?
相当于Nullable<bool>
.
bool
is a value type, this means that it cannot be null
, so the Nullable type basically allows you to wrap value types, and being able to assign null
to them.
bool
是值类型,这意味着它不能是null
,因此 Nullable 类型基本上允许您包装值类型,并能够分配null
给它们。
bool?
can contain three different values: true
, false
and null
.
bool?
可以包含三个不同的值:true
,false
和null
。
Also, there are no short-circuiting operators (&& ||) defined for bool?
此外,没有为以下定义的短路运算符 (&& ||) bool?
Only the logical AND, inclusive OR, operators are defined and they behave like this:
仅定义了逻辑 AND、包含 OR 和运算符,它们的行为如下:
x y x & y x | y
true true true true
true false false true
true null null true
false true false true
false false false false
false null false null
null true null true
null false false null
null null null null
The Nullable type is basically a generic struct, that has the following public properties:
Nullable 类型基本上是一个通用结构,具有以下公共属性:
public struct Nullable<T> where T: struct
{
public bool HasValue { get; }
public T Value { get; }
}
The HasValue
property indicates whether the current object has a value, and the Value
property will get the current value of the object, or if HasValue is false, it will throw an InvalidOperationException.
该HasValue
属性表示当前对象是否有值,该Value
属性会获取该对象的当前值,如果HasValue为false,则抛出InvalidOperationException。
Now you must be wondering something, Nullable is a struct, a value type that cannot be null, so why the following statement is valid?
现在你一定很奇怪,Nullable 是一个结构体,一个不能为空的值类型,那么为什么下面的语句是有效的呢?
int? a = null;
That example will compile into this:
该示例将编译为:
.locals init (valuetype [mscorlib]System.Nullable`1<int32> V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj valuetype [mscorlib]System.Nullable`1<int32>
A call to initobj, which initializes each field of the value type at a specified address to a null reference or a 0 of the appropriate primitive type.
对initobj的调用,它将指定地址处的值类型的每个字段初始化为空引用或适当原始类型的 0。
That's it, what's happening here is the default struct initialization.
就是这样,这里发生的是默认的结构初始化。
int? a = null;
Is equivalent to:
相当于:
Nullable<int> a = new Nullable<int>();
回答by Fredrik M?rk
bool?
is nullable while bool
is not.
bool?
可以为空,而bool
不能为空。
bool? first;
bool second;
In the above code, first
will be null
while second
will be false
.
在上面的代码中,first
will be null
while second
will be false
。
One typical use is if you want to know whether there has been an assignment made to the variable. Since bool
is a value type(just as int
, long
, double
, DateTime
and some other types), it will always be initialized to a default value (false
in the case of a bool
, 0
in the case of an int
). This means that you can not easily know whether it's false
because some code assigned false
to it, or if it is false
because it has not yet been assigned. In that case bool?
comes in handy.
一种典型用途是,如果您想知道是否对变量进行了赋值。由于bool
是一个值类型(正如int
,long
,double
,DateTime
和一些其他类型),它将总是被初始化为默认值(false
在的情况下bool
,0
在的情况下int
)。这意味着您无法轻易知道是false
因为某些代码被分配false
给它,还是false
因为它尚未被分配。在这种情况下bool?
就派上用场了。
回答by JaredPar
Whenever you see the ? character following a type name, it's shorthand for Nullable<TypeName>
. Nullable is a special type that allows value types to act like a null value. It's a way of explicitly expressing a value type can have a non-value value.
每当你看到 ? 类型名称后面的字符,它是Nullable<TypeName>
. Nullable 是一种特殊类型,它允许值类型像空值一样工作。它是一种显式表达值类型的方法,可以具有非值值。
For bool it effectively turns the variable into a tri-state value
对于 bool 它有效地将变量转换为三态值
- With Value: True
- With Value: False
- Without Value
- 值:真
- 带值:假
- 没有价值
回答by RaYell
bool
can contain only true
and false
values while bool?
can also have a null
value.
bool
只能包含true
和false
值,同时bool?
也可以有null
值。
回答by Charlie
bool? means the boolean is nullable and is syntactic sugar for a stucture Nullable<bool>
. Because a boolean is a value type, you cannot set it to null, but there are some cases where you'd want to like in a data access class because database fields can have null values.
布尔?意味着布尔值可以为空,并且是结构的语法糖Nullable<bool>
。因为布尔值是一种值类型,所以不能将其设置为 null,但在某些情况下,您希望在数据访问类中使用它,因为数据库字段可以具有 null 值。
回答by Kredns
Adding ?
makes the type null-able. Which means you can do this:
添加?
使类型可以为空。这意味着你可以这样做:
bool? x = null;
And it would be totally OK.
它会完全没问题。
回答by Kredns
bool means you can have values of true and false. bool? means you can have a value of true, false, and null.
bool 意味着您可以拥有 true 和 false 值。布尔?意味着您可以拥有 true、false 和 null 值。
It works for datetime and booleans.
它适用于日期时间和布尔值。
回答by EricM
Another good place to use bool? is in a method to add null checking
另一个使用 bool 的好地方?正在添加空检查的方法中
public bool? IsTurkeyStillInFridge(Turkey turkey)
{
if (turkey == null)
return null;
else if (fridge.Contains(turkey))
return true;
else
return false;
}
bool? canStayAtDesk = IsTurkeyStillInFridge(turkey);
if (canStayAtDesk == null)
MessageBox.Show("No turkey this year, check for ham.");
else if (canStayAtDesk == true)
MessageBox.Show("Turkey for lunch. Stay at desk.");
else
MessageBox.Show("Turkey's gone, go out to lunch.");