Csharp 简明教程
C
C# 提供了一个特殊的数据类型,即 nullable 类型,你可以向其分配正常值范围以及空值。
C# provides a special data types, the nullable types, to which you can assign normal range of values as well as null values.
例如,你可以在一个 Nullable<Int32> 变量中存储从 -2,147,483,648 到 2,147,483,647 内的任何值,或者存储空值。同样,你可以在一个 Nullable<bool> 变量中分配 true、false 或 null。声明 nullable 类型的语法如下 −
For example, you can store any value from -2,147,483,648 to 2,147,483,647 or null in a Nullable<Int32> variable. Similarly, you can assign true, false, or null in a Nullable<bool> variable. Syntax for declaring a nullable type is as follows −
< data_type> ? <variable_name> = null;
以下示例演示了空值数据类型的用法 −
The following example demonstrates use of nullable data types −
using System;
namespace CalculatorApplication {
class NullablesAtShow {
static void Main(string[] args) {
int? num1 = null;
int? num2 = 45;
double? num3 = new double?();
double? num4 = 3.14157;
bool? boolval = new bool?();
// display the values
Console.WriteLine("Nullables at Show: {0}, {1}, {2}, {3}", num1, num2, num3, num4);
Console.WriteLine("A Nullable boolean value: {0}", boolval);
Console.ReadLine();
}
}
}
编译并执行上述代码后,将产生以下结果 −
When the above code is compiled and executed, it produces the following result −
Nullables at Show: , 45, , 3.14157
A Nullable boolean value:
The Null Coalescing Operator (??)
空合并运算符与可空值类型和引用类型一起使用。它用于将一个操作数转换为另一种可空(或不可空)值类型操作数的类型,此时可以进行隐式转换。
The null coalescing operator is used with the nullable value types and reference types. It is used for converting an operand to the type of another nullable (or not) value type operand, where an implicit conversion is possible.
如果第一个操作数的值为 null,则该运算符返回第二个操作数的值,否则,它将返回第一个操作数的值。以下示例对此进行了说明 −
If the value of the first operand is null, then the operator returns the value of the second operand, otherwise it returns the value of the first operand. The following example explains this −
using System;
namespace CalculatorApplication {
class NullablesAtShow {
static void Main(string[] args) {
double? num1 = null;
double? num2 = 3.14157;
double num3;
num3 = num1 ?? 5.34;
Console.WriteLine(" Value of num3: {0}", num3);
num3 = num2 ?? 5.34;
Console.WriteLine(" Value of num3: {0}", num3);
Console.ReadLine();
}
}
}
编译并执行上述代码后,将产生以下结果 −
When the above code is compiled and executed, it produces the following result −
Value of num3: 5.34
Value of num3: 3.14157