在类型转换中执行 C# Null 检查的简单方法

Ano*_*per 5 c# entity-framework c#-5.0 .net-4.5

我正在一个我不太熟悉的项目中进行一些快速类型转换。

它们看起来类似于:

var NewType = new
{
    NewTypeId = old.SubType == null ? 0 : old.SubType.SubTypeId ?? 0,
    OtherType = old.OtherType ?? "",
    Review = old.CustomerComments ?? "",
    Country = old.Country == null ? "" : old.Country.Abbreviation ?? "",
    Customer = old.SubType == null ? "" :
                    old.SubType.Customer == null ? "" :
                        old.SubType.Customer.Name ?? ""
};
Run Code Online (Sandbox Code Playgroud)

我要转换的对象通常是实体框架对象。我也没有能力修改我将要转换形式的类。

是否有更简单的方法来检查空值,特别是对于任何子对象可能为空的情况?

OldType.SubType.AnotherSubType.SomeProperty
Run Code Online (Sandbox Code Playgroud)

Ren*_*ogt 3

从 C# 6 开始,您可以使用null 传播/null 条件运算符

var NewType = new
{
    NewTypeId = old.SubType?.SubTypeId ?? 0,
    OtherType = old.OtherType ?? "",
    Review = old.CustomerComments ?? "",
    Country = old.Country?.Abbreviation ?? "",
    Customer = old.SubType?.Customer?.Name ?? ""
};
Run Code Online (Sandbox Code Playgroud)

如果你有这样的课程

public class Example
{
    public int Value {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

和一个实例

Example sample = GetExample();
Run Code Online (Sandbox Code Playgroud)

那么这个表达式:

sample?.Value
Run Code Online (Sandbox Code Playgroud)

返回一个Nullable<int>. 其值为Valueif samplewas notnull或没有值 (is null) if samplewas null

  • 但不是在表达中。 (2认同)