【问题标题】:Easy Way to Perform C# Null Check in a Type Conversion在类型转换中执行 C# Null 检查的简单方法
【发布时间】:2019-06-18 01:15:37
【问题描述】:

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

它们看起来像这样:

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 ?? ""
};

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

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

OldType.SubType.AnotherSubType.SomeProperty

【问题讨论】:

  • 您使用的是什么版本的 .NET(即 C#)?
  • C# 5 (.Net 4.5)
  • 你能直接从IQueryable创建新类型吗? (即投影)那时你不需要空检查。
  • @rory.ap .NET 版本无关; C# 版本很重要。 .NET 版本和 C# 版本完全分开。
  • @GertArnold 嗯,我得考虑一下。我有一个已经创建的对象,我正在使用它进行转换,但我可能会做你建议的事情。

标签: c# entity-framework .net-4.5 c#-5.0


【解决方案1】:

从 C# 6 开始,您可以使用 null-propagation/null-conditional operator:

var NewType = new
{
    NewTypeId = old.SubType?.SubTypeId ?? 0,
    OtherType = old.OtherType ?? "",
    Review = old.CustomerComments ?? "",
    Country = old.Country?.Abbreviation ?? "",
    Customer = old.SubType?.Customer?.Name ?? ""
};

如果你有类似的课程

public class Example
{
    public int Value {get; set;}
}

还有一个实例

Example sample = GetExample();

那么这个表达式:

sample?.Value

返回Nullable<int>。如果sample 不是null,则其值为Value;如果samplenull,则其没有值(为null)。

【讨论】:

  • 不在表达式中。
  • @IvanStoev 对,忘记了,可能是因为 OP 没有明确提到它需要在表达式中工作。
  • 我正在使用表达式,但如果像 Automapper 这样的东西可以帮助解决这个问题,那也可以。我正在开发一个我在项目后期不熟悉的应用程序,并且正在寻找一种简单的方法来进行一些小的辅助更改,并尽可能减少占用空间。
猜你喜欢
  • 2011-01-22
  • 2019-05-06
  • 1970-01-01
  • 1970-01-01
  • 2010-10-07
  • 1970-01-01
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
相关资源
最近更新 更多