类型后面的问号有什么作用(例如:int?myVariable)? [英] What is the purpose of a question mark after a type (for example: int? myVariable)?
问题描述
通常问号的主要用途是用于条件,x ?是":否"
.
Typically the main use of the question mark is for the conditional, x ? "yes" : "no"
.
但我已经看到了它的另一种用法,但找不到对 ?
运算符的这种用法的解释,例如.
But I have seen another use for it but can't find an explanation of this use of the ?
operator, for example.
public int? myProperty
{
get;
set;
}
推荐答案
这意味着有问题的值类型是 可空类型
It means that the value type in question is a nullable type
Nullable 类型是 System.Nullable 结构的实例.一种可为空类型可以表示其正确的值范围基础值类型,加上一个额外的空值.例如,一个Nullable
,读作Nullable of Int32",可以赋值给任何值从 -2147483648 到 2147483647,或者可以赋值为空价值.可以为 Nullable
分配值 true、false 或空值.将 null 分配给数字和布尔类型的能力是在处理数据库和其他数据时特别有用包含可能未赋值的元素的类型.为了例如,数据库中的布尔字段可以存储值 true 或false,否则可能未定义.
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<Int32>
, pronounced "Nullable of Int32," can be assigned any value from -2147483648 to 2147483647, or it can be assigned the null value. ANullable<bool>
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.
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);
}
}
}
这篇关于类型后面的问号有什么作用(例如:int?myVariable)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!