有没有办法在C#5中模仿C#6空条件运算符 [英] Is there a way to Imitate C# 6 Null-Conditional operator in C# 5

查看:48
本文介绍了有没有办法在C#5中模仿C#6空条件运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到一种情况,我需要在对象初始化程序中分配一些对象的属性.这些对象中的一些可以为null,我需要访问它们的属性,问题是它们太多了,并且使用if/else不好.

示例

  visits = visitJoins.AsEnumerable().Select(joined => new VisitPDV(){VisiteId = join.Visite.VisiteId.ToString(),NomPointDeVente = Joined.VisitePdvProduit.PointDeVente.NomPointDeVente,}); 

joined.VisitePdvProduit 可以为null,问题是有数十种这样的分配(我只是为了缩短代码而已)

对于这种情况, C#6 Null-Conditional运算符是完美的解决方案,问题是我使用的是 C#5 这个项目,有什么方法可以模仿吗?

解决方案

好吧,您可以使用扩展方法来接收访问者委托,并且仅在该项目不是 null 时才执行:/p>

 公共静态TResult ConditionalAccess< TItem,TResult>(此TItem项,Func< TItem,TResult>访问器),其中TResult:类{如果(item == null){返回null;}别的{返回访问器(项目);}} 

您可以像这样使用它:

  NomPointDeVente = join.VisitePdvProduit.ConditionalAccess(_ => _.PointDeVente.NomPointDeVente); 

对于不返回值的操作(即 bar.ConditionalAccess(_ => _.Foo()))或返回值类型,您可以轻松创建此方法的版本./p>

I have a situation where I need to assign some objects' properties inside an object initializer. Some of these objects can be null and I need to access their properties, the problem is that they are too many, and using a if/else thing is not good.

Example

visits = visitJoins.AsEnumerable().Select(joined => new VisitPDV()
{
    VisiteId = joined.Visite.VisiteId.ToString(),
    NomPointDeVente = joined.VisitePdvProduit.PointDeVente.NomPointDeVente,             
});

The joined.VisitePdvProduit can be null, and the problem is that there are like dozens of such assignments (I just took one to shorten the code)

The C# 6 Null-Conditional operator is the perfect solution for this situation, the problem is that I'm on C# 5 in this project, is there a way to imitate that ?

解决方案

Well, you can use an extension method that receives an accessor delegate and only executes it if the item isn't null:

public static TResult ConditionalAccess<TItem, TResult>(this TItem item, Func<TItem, TResult> accessor) where TResult : Class
{
    if (item == null)
    {
        return null;
    }
    else
    {
        return accessor(item);
    }
}

You can use it for example like this:

NomPointDeVente = joined.VisitePdvProduit.ConditionalAccess(_ => _.PointDeVente.NomPointDeVente);

You can easily create versions of this method for operations that don't return a value (i.e. bar.ConditionalAccess(_ => _.Foo())) or return value types.

这篇关于有没有办法在C#5中模仿C#6空条件运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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