在 C# 中,可空类型允许我们将 null
赋给变量。例如,
Nullable<int> x = null;
在这里,我们将 null
值赋给了整型变量 x
。
声明可空类型
在 C# 中,我们可以这样声明可空类型:
Nullable<dataType> variableName = null;
这里,dataType
是 **值数据类型**,如浮点型、整型、布尔型等。
声明可空类型的另一种方法
使用 ? 运算符声明可空类型
我们也可以使用 ?
运算符声明 Nullable
类型,如下所示:
datatype? variableName = null;
例如,
int? x = null;
为什么需要可空类型?
在 C# 中,我们不能直接将 null 值赋给变量类型。例如:
using System;
class Program
{
public static void Main()
{
// assigning 'null' to x
int x = null;
Console.WriteLine(x);
}
}
此代码会引发编译器错误
Cannot convert null to 'int' because it is a non-nullable value type
所以,在这种情况下,我们使用 Nullable
类型将 null
赋给变量,如下所示:
using System;
class Program
{
public static void Main()
{
// assigning 'null' to x
Nullable<int> x = null;
Console.WriteLine(x);
}
}
上面的程序不会引发错误。
访问可空类型
要访问 Nullable
类型的值,我们使用 GetValueOrDefault()
方法。例如:
using System;
class Program
{
public static void Main()
{
// assigning 'null' to integer type variable x
Nullable<int> x = null;
// access Nullable type
Console.WriteLine("Value of x: " + x.GetValueOrDefault());
}
}
输出
Value of x: 0
在上面的示例中,我们将 null
赋给了整型变量 x
。
不同数据类型的可空类型
在 C# 中,Nullable
类型仅适用于值数据类型,如整型、浮点型、布尔型等。例如:
using System;
class Program
{
public static void Main()
{
// assigning 'null' to integer type variable x
Nullable<int> x = null;
// assigning 'null' to boolean type variable y
Nullable<bool> y = null;
// assigning 'null' to floating point type variable z
Nullable<float> z = null;
// access Nullable types
Console.WriteLine("Value of x: " + x.GetValueOrDefault());
Console.WriteLine("Value of y: " + y.GetValueOrDefault());
Console.WriteLine("Value of z: " + z.GetValueOrDefault());
}
}
输出
Value of x: 0 Value of y: False Value of z: 0
在这里,我们将 null
赋给了不同类型的变量。
常见问题
可空类型的赋值规则
我们在声明变量时必须为可空类型赋值。否则,程序将产生编译时错误。例如:
using System;
class Program
{
public static void Main()
{
// a is not assigned with any value
Nullable<int> a;
Console.WriteLine(a);
}
}
错误
Use of unassigned local variable 'a'
如何检查变量是否已赋值?
我们可以使用 Nullable.HasValue
或 Nullable.Value
来检查变量是否已赋值。它返回:
True
- 如果变量已赋值False
- 如果变量被赋值为null
并且,如果变量未赋值,则会引发编译时错误。例如:
using System;
class Program
{
public static void Main()
{
// x is assigned with a value
Nullable<int> x = 5;
// y is assigned with null value
Nullable<int> y = null;
// returns True since x is assigned with a value
Console.WriteLine(x.HasValue);
// returns False since y is assigned with a null value
Console.WriteLine(y.HasValue);
}
}
输出
True False