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

时间:2016-12-27 17:24:37

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

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

它们看起来与此相似:

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

我正在转换的对象通常是Entity Framework对象。我也没有能力修改我将要转换的表格。

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

OldType.SubType.AnotherSubType.SomeProperty

1 个答案:

答案 0 :(得分:3)

从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>。如果Value不是sample,则null的值为null,如果samplenull,则<amp-accordion> <section> <h4>Section 1</h4> <p>Bunch of content.</p> </section> <section> <h4>Section 2</h4> <amp-accordion class="nested-accordion"> <section> <h4>Nested Section 2.1</h4> <p>Bunch of content.</p> </section> <section> <h4>Nested Section 2.2</h4> <p>Bunch of more content.</p> </section> </amp-accordion> </section> 没有值$body = $this->get_body_node(); // Build our amp-ad tag $ad_node = AMP_DOM_Utils::create_node( $this->dom, 'amp-ad', array( 'width' => 300, 'height' => 250, 'type' => 'ad', 'data-ad-client' => '###', 'data-ad-slot' => '###' ) ); // Add a placeholder to show while loading $fallback_node = AMP_DOM_Utils::create_node( $this->dom, 'amp-img', array( 'placeholder' => '', 'layout' => 'fill', 'src' => 'https://placehold.it/300X250', ) ); $ad_node->appendChild( $fallback_node ); $p_nodes = $body->getElementsByTagName( 'p' ); $pListLength = $p_nodes->length; if ( $pListLength > 5 ) { for($i=5; $i <= $pListLength; $i+=5) { $p_nodes->item($i)->parentNode->insertBefore( $ad_node, $p_nodes->item($i)); } } 。< / p>