gpt4 book ai didi

c# - C# 中的 Nullsafe 导航

转载 作者:太空狗 更新时间:2023-10-29 20:28:50 24 4
gpt4 key购买 nike

<分区>

Possible Duplicates:
Safe Navigation Operator in C#?
Shortcut for “null if object is null, or object.member if object is not null”

在我的 XML 处理项目中,我必须浏览链式属性以获得所需的值。例如,obj1.obj2.obj3.obj4.obj....Value。并且此链中的任何对象都可能为空。

我在 google 上搜索了“C# 中的 NullSafe 导航”并找到了一些不错的文章。来自 Post 之一,我有了实现自定义扩展的想法。现在我对这个扩展的性能有疑问。我有这3个解决方案。谁能建议我最好采用哪一个(就性能而言)?

  • 选项 1(使用 logic explained on this article ):

    //custom extension method
    public static TOutput IfNotNull<TInput, TOutput>(this TInput x, Func<TInput, TOutput> f)
    where TInput : class
    where TOutput : class
    {
    return x == null ? null : f(x);
    }

    //with custom extension method -- Very neat & clean.. but what about performance?
    string x = obj1
    .IfNotNull(x => x.obj2)
    .IfNotNull(x => x.obj3)
    .IfNotNull(x => x.obj4)
    .IfNotNull(x => x.obj5)
    .IfNotNull(x => x.Value);
  • 选项 2:

    //with NullCheck  -- probably right way?
    if(obj1 != null
    && obj1.obj2 != null
    && obj1.obj2.obj3 != null
    && obj1.obj2.obj3.obj4 != null
    && obj1.obj2.obj3.obj4.obj5 != null)
    {
    string x = obj1.obj2.obj3.obnj4.obj5.Value;
    }
  • 选项 3:

    //with try-catch.. With lowest cyclomatic complexity, but not a right approach.
    try
    {
    string x = obj1.obj2.obj3.obnj4.obj5.Value;
    }
    catch(NullReferenceException ne)
    {
    //ignore exception
    }

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com