可空类型Nullable用法详解
可空类型Nullable用法详解
概述
C# 提供了可空类型 Nullable<T> 来表示值类型(例如 int、double 等)可以为 null。可空类型的变量将具有两种可能的状态:1)具有值;2)没有值(null)。
int? myNullableInt = null; // 可空类型 int 的变量,赋值为 null(没有值)可空类型的变量与普通值类型的变量一样使用,但需要注意可空类型变量可能为 null,因此在使用时需判断是否为 null。
if (myNullableInt.HasValue){ int myInt = myNullableInt.Value; Console.WriteLine("变量myNullableInt有值,值为:" + myInt);}else{ Console.WriteLine("变量myNullableInt没有值");}应用
1. 数据库中的 null 值
在读取数据库中的数据时,有些列允许存储 null 值。如果直接读取该列的值并转换为值类型,若该列中存储了 null 值,则会报错。此时,可以使用可空类型来解决这个问题。
using System.Data.SqlClient;// ...using (SqlConnection connection = new SqlConnection(connectionString)){ string sql = "SELECT SomeColumn FROM SomeTable WHERE Id = 1"; SqlCommand command = new SqlCommand(sql, connection); connection.Open(); SqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { int? someValue = reader.IsDBNull(0) ? (int?)null : reader.GetInt32(0); Console.WriteLine("someValue 的值为:" + (someValue.HasValue ? someValue.Value.ToString() : "空")); } else { Console.WriteLine("没有读取到数据"); }}2. 方法的返回值可能为 null
在编写方法时,有时需要返回一个值类型的数据,但由于某些原因,方法可能无法返回数据,此时可以使用可空类型来处理这种场景。
static int? Divide(int pidend, int pisor){ if (pisor == 0) { return null; } return pidend / pisor;}// ...int? result = Divide(1, 0);if (result.HasValue){ Console.WriteLine("计算结果为:" + result);}else{ Console.WriteLine("除数不能为 0");}结论
可空类型 Nullable<T> 是 C# 中的一个重要特性,可以有效地帮助处理值类型可能为 null 的场景。使用可空类型时,需要注意需判断是否为 null,否则可能引发 null 引用异常。