c# – 读取对象的子属性的优雅方式

假设您正在阅读此属性

var town = Staff.HomeAddress.Postcode.Town;

沿着链的某处可能存在null。
什么是最好的阅读城镇的方式?

我一直在试验几种扩展方法…

public static T2 IfNotNull<T1, T2>(this T1 t, Func<T1, T2> fn) where T1 : class
{
    return t != null ? fn(t) : default(T2);
}

var town = staff.HomeAddress.IfNotNull(x => x.Postcode.IfNotNull(y=> y.Town));

要么

public static T2 TryGet<T1, T2>(this T1 t, Func<T1, T2> fn) where T1 : class
{
if (t != null)
{
    try
    {
        return fn(t);
    }
    catch{ }
}
return default(T2);
}

var town = staff.TryGet(x=> x.HomeAddress.Postcode.Town);

显然,这些只是抽象出逻辑和使代码(一点点)更可读。

但是有没有更好的/更有效的方法?

编辑:

在我的特定情况下,对象从WCF服务返回,我不能控制这些对象的体系结构。

编辑2:

还有这种方法:

public static class Nullify
{
    public static TR Get<TF, TR>(TF t, Func<TF, TR> f) where TF : class
    {
        return t != null ? f(t) : default(TR);
    }

    public static TR Get<T1, T2, TR>(T1 p1, Func<T1, T2> p2, Func<T2, TR> p3)
        where T1 : class
        where T2 : class
    {
        return Get(Get(p1, p2), p3);
    }

    /// <summary>
    /// Simplifies null checking as for the pseudocode
    ///     var r = Pharmacy?.GuildMembership?.State?.Name
    /// can be written as
    ///     var r = Nullify( Pharmacy, p => p.GuildMembership, g => g.State, s => s.Name );
    /// </summary>
    public static TR Get<T1, T2, T3, TR>(T1 p1, Func<T1, T2> p2, Func<T2, T3> p3, Func<T3, TR> p4)
        where T1 : class
        where T2 : class
        where T3 : class
    {
        return Get(Get(Get(p1, p2), p3), p4);
    }
}

从这篇文章http://qualityofdata.com/2011/01/27/nullsafe-dereference-operator-in-c/

最好的办法是避免违反law of Demeter

var town = Staff.GetTown();

和在员工:

string GetTown()
{
    HomeAddress.GetTown();
}

并在HomeAddress:

string GetTown()
{
    PostCode.GetTown();
}

并在PostCode中:

string GetTown()
{
    Town.GetTownName();
}

更新:

由于你没有控制权,你可以使用short circuit evaluation

if(Staff != null 
   && Staff.HomeAddress != null
   && Staff.HomeAddress.PostCode != null
   && Staff.HomeAddress.PostCode.Town != null)
{
    var town = Staff.HomeAddress.Postcode.Town;
}
http://stackoverflow.com/questions/5744640/elegant-way-of-reading-a-child-property-of-an-object

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:c# – 读取对象的子属性的优雅方式