转载请注明来自我的优快云博客:黄朝辉的博客
这里记录下c#里的这个Nullable类型,因为以前在其它语言里并没见过。
首先还是看MSDN上的说法:
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. A Nullable can be assigned the values truefalse, 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.
译:Nullable类型是System.Nullable 结构的实例,一个nullable类型能代表它下面的值的正确范围,还能取null值。例如: a Nullable读音:”Nullable of Int32,”,可以取 -2147483648 到 2147483647范围的值,也可赋值为null。同样,Nullable 可以取true,false还有null。在与数据库打交道的时候,能给numeric和Boolean类型取null值特别有用,包含元素的其它数据类型可能没被赋值。例如:一个在数据库Boolean域可以存true和false,也可能是未定义(null)。
以下为一个简单的代码示例:
static void Main(string[] args)
{
int? num = null;
if (num.HasValue)
{
System.Console.WriteLine("num = " + num.Value);
}
else
{
System.Console.WriteLine("num = Null");
}
}