What is the purpose of a question mark after a type (for example: int? myVariable)?
通常问号的主要用途是用于有条件的
但是我已经看到了它的另一个用途,但是找不到对
1 2 3 4 5 | public int? myProperty { get; set; } |
这意味着所讨论的值类型是可以为空的类型
Nullable types are instances of the System.Nullable struct. A
nullable type can represent the correct range of values for its
underlying value type, plus an additional null value. For example, a
Nullable , pronounced"Nullable of Int32," can be assigned any
value from -2147483648 to 2147483647, or it can be assigned the null
value. ANullable can be assigned the values true, false, or
null. The ability to assign null to numeric and Boolean types is
especially useful when you are dealing with databases and other data
types that contain elements that may not be assigned a value. For
example, a Boolean field in a database can store the values true or
false, or it may be undefined.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30 class NullableExample
{
static void Main()
{
int? num = null;
// Is the HasValue property true?
if (num.HasValue)
{
System.Console.WriteLine("num =" + num.Value);
}
else
{
System.Console.WriteLine("num = Null");
}
// y is set to zero
int y = num.GetValueOrDefault();
// num.Value throws an InvalidOperationException if num.HasValue is false
try
{
y = num.Value;
}
catch (System.InvalidOperationException e)
{
System.Console.WriteLine(e.Message);
}
}
}
它是
在
1 | x ?"yes" :"no" |
这个?声明if语句。这里:x代表布尔条件;在:前面的部分是then语句,后面的部分是else语句。
例如,在
1 | int? |
这个?声明一个可为空的类型,并表示其前面的类型可能具有空值。
Nullable Types
Nullable types are instances of the
System.Nullable struct. A nullable
type can represent the normal range of
values for its underlying value type,
plus an additional null value. For
example, a [Nullable ], pronounced
"Nullable of Int32," can be assigned
any value from -2147483648 to
2147483647, or it can be assigned the
null value. A [Nullable ] can be
assigned the values true or false, or
null. The ability to assign null to
numeric and Boolean types is
particularly useful when dealing with
databases and other data types
containing elements that may not be
assigned a value. For example, a
Boolean field in a database can store
the values true or false, or it may be
undefined.
它声明该类型可以为空。
实际用途:
1 2 3 4 5 6 7 8 9 | public string someFunctionThatMayBeCalledWithNullAndReturnsString(int? value) { if (value == null) { return"bad value"; } return someFunctionThatHandlesIntAndReturnsString(value); } |
为了补充上述答案,这里有一个代码示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
这将导致编译错误:
Error 12 Cannot convert null to 'Test' because it is a non-nullable
value type
请注意,nullabletest没有编译错误。(注意)?在t2的声明中)
如果您不知道:值类型是接受值为
它们不能接受对值的引用:如果您给它们分配一个
你为什么需要那个?因为有时您的值类型变量可能会收到一些工作不太好的返回的空引用,比如从数据库返回的丢失或未定义的变量。
我建议您阅读微软文档,因为它很好地涵盖了这个主题。