阅读对象的子属性优雅的方式 [英] Elegant way of reading a child property of an object

查看:125
本文介绍了阅读对象的子属性优雅的方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你正在尝试读取此属性。

Say you are trying to read this property

var town = Staff.HomeAddress.Postcode.Town;



沿链某处一个空的可能存在。
什么是阅读镇上最好的方法是什么?

Somewhere along the chain a null could exist. What would be the best way of reading Town?

我一直在尝试与一对夫妇的扩展方法...

I have been experimenting with a couple of extension methods...

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);



显然,这些都只是抽象掉的逻辑和使代码(略)更具可读性。

Obviously these are just abstracting away the logic and making the code (a little) more readable.

但有一个更好/更有效的方式。

But is there a better/ more efficient way?

编辑:

在我的具体情况正在从WCF服务返回的对象,我必须对这些对象的架构无法控制

In my particular case the objects are being returned from a WCF service and I have no control over the architecture of those objects.

编辑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 /

推荐答案

最好的办法是避免违反的德米特的法律。

The best way would be to avoid violating the law of Demeter.

var town = Staff.GetTown();



而在员工

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



而在是homeAddress

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



而在邮编

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






更​​新:


Update:

既然你没有控制权,你可以使用的短路评价

Since you don't have control over this, you can use short circuit evaluation:

if(Staff != null 
   && Staff.HomeAddress != null
   && Staff.HomeAddress.PostCode != null
   && Staff.HomeAddress.PostCode.Town != null)
{
    var town = Staff.HomeAddress.Postcode.Town;
}

这篇关于阅读对象的子属性优雅的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆