获取可空变量的值或空值
Get value or null of nullable variable
使用 C# 6 我有以下模型:
public class Model {
public Int32? Result { get; set; }
}
我有以下(示例代码):
Model model = new Model();
Int32 result = model.Result.Value;
如果结果为空,我会得到一个错误,所以我需要使用:
Int32 result = model.Result.HasValue ? model.Result.Value : 0;
在 C# 6 中是否有更短的方法来执行此操作?
您可以将 null 传播运算符与 null 条件运算符结合使用来提供默认值。
Model modelWithNullValue = new Model();
Model modelWithValue = new Model { Result = 1};
Model modelThatIsNull = null;
Int32 resultWithNullValue = modelWithNullValue?.Result ?? -1;
Int32 resultWithValue = modelWithValue?.Result ?? -1;
Int32 resultWithNullModel = modelThatIsNull?.Result ?? -2;
Console.WriteLine(resultWithNullValue); // Prints -1
Console.WriteLine(resultWithValue); // Prints 1
Console.WriteLine(resultWithNullModel); // Prints -2
编辑:从 C# 7.2 开始,以下语法也适用于在这种情况下设置默认值。
Model badModel = null;
var result = badModel?.Result ?? default;
var pre72 = badModel?.Result ?? default(int);
Console.WriteLine(result); // 0
Console.WriteLine(result.GetType().Name); // Int32
使用 C# 6 我有以下模型:
public class Model {
public Int32? Result { get; set; }
}
我有以下(示例代码):
Model model = new Model();
Int32 result = model.Result.Value;
如果结果为空,我会得到一个错误,所以我需要使用:
Int32 result = model.Result.HasValue ? model.Result.Value : 0;
在 C# 6 中是否有更短的方法来执行此操作?
您可以将 null 传播运算符与 null 条件运算符结合使用来提供默认值。
Model modelWithNullValue = new Model();
Model modelWithValue = new Model { Result = 1};
Model modelThatIsNull = null;
Int32 resultWithNullValue = modelWithNullValue?.Result ?? -1;
Int32 resultWithValue = modelWithValue?.Result ?? -1;
Int32 resultWithNullModel = modelThatIsNull?.Result ?? -2;
Console.WriteLine(resultWithNullValue); // Prints -1
Console.WriteLine(resultWithValue); // Prints 1
Console.WriteLine(resultWithNullModel); // Prints -2
编辑:从 C# 7.2 开始,以下语法也适用于在这种情况下设置默认值。
Model badModel = null;
var result = badModel?.Result ?? default;
var pre72 = badModel?.Result ?? default(int);
Console.WriteLine(result); // 0
Console.WriteLine(result.GetType().Name); // Int32