如何有用的是C#的?运营商? [英] How useful is C#'s ?? operator?

查看:122
本文介绍了如何有用的是C#的?运营商?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我已经被好奇?操作者,但仍无法使用它。我通常会想到它的时候,我做这样的事情:

So I have been intrigued by the ?? operator, but have still been unable to use it. I usually think about it when I am doing something like:

var x = (someObject as someType).someMember;

如果someObject是有效的,someMember是空的,我可以做

If someObject is valid and someMember is null, I could do

var x = (someObject as someType).someMember ?? defaultValue;

但几乎无一例外地我进入问题时,someObject为空,且?不帮我做这个的任何比做空检查自己的清洁剂。

but almost invariably I get into problems when someObject is null, and ?? doesn't help me make this any cleaner than doing the null check myself.

使用什么有你们找到了?在实际情况呢?

What uses have you guys found for ?? in practical situations?

推荐答案

我同意你的?运营商通常是有限use--是非常有用的提供回退值,如果事情是空的,但如果你想继续往下钻成属性或方法是没有用的,以prevent的情况下一个空引用异常一个有时空引用。

I agree with you that the ?? operator is usually of limited use-- it's useful to provide a fall-back value if something is null, but isn't useful to prevent a Null Reference Exception in cases when you want to continue drilling down into properties or methods of a sometimes-null reference.

恕我直言,我们所需要的远不止?是一个空解引用操作符,让您链长属性和/或方法链在一起,例如 A·B()。c.d()即无需测试空岬每个中间步骤。该的Groovy语言拥有的安全航行运营商,这是非常方便的。

IMHO, what's needed much more than ?? is a "null-dereference" operator which allows you to chain long property and/or method chains together, e.g. a.b().c.d().e without having to test each intermediate step for null-ness. The Groovy language has a Safe Navigation operator and it's very handy.

幸运的是,似乎C#团队已经意识到这个功能的差距。见C#团队添加一个空值这个 connect.microsoft.com建议解引用操作符的C#语言。

Luckily, it seems that the C# team is aware of this feature gap. See this connect.microsoft.com suggestion for the C# team to add a null-dereference operator to the C# language.

我们得到相当多的请求为
  功能与此类似。中的?。
  版本在社会上提到的
  讨论是最接近我们的心 -
  它可以让你在测试空
  每一个点,并与很好地构成
  现有的?运营商:

We get quite a number of requests for features similar to this one. The "?." version mentioned in the community discussion is closest to our hearts - it allows you to test for null at every "dot", and composes nicely with the existing ?? operator:

一个?.B?.C? ð

a?.b?.c ?? d

含义如有一,A·B或A.B.C是
  空用D来代替。

Meaning if any of a , a.b or a.b.c is null use d instead.

我们正在考虑这为未来的
  释放,但它不会在C#4.0。

We are considering this for a future release, but it won't be in C# 4.0.

再次感谢,

的Mads托格森,C#语言PM

Mads Torgersen, C# Language PM

如果你也想在C#中此功能,请将您的票到建议在Connect网站! : - )

If you also want this feature in C#, add your votes to the suggestion on the connect site! :-)

一个解决方法我用它来解决缺少此功能就像是什么在<所描述的扩展方法href=\"http://blogs.infosupport.com/blogs/frankb/archive/2008/02/02/Using-C_2300_-3.0-Extension-methods-and-Lambda-ex$p$pssions-to-avoid-nasty-Null-Checks.aspx\"相对=nofollow>这个博客帖子,让code是这样的:

One workaround I use to get around the lack of this feature is an extension method like what's described in this blog post, to allow code like this:

string s = h.MetaData
            .NullSafe(meta => meta.GetExtendedName())
            .NullSafe(s => s.Trim().ToLower())

这code或者返回 h.MetaData.GetExtendedName()。修剪()。ToLower将()或返回null如果h,h.MetaData,或h.MetaData.GetExtendedName()为null。我也扩展了这一检查null或空字符串,或空或空的集合。这里是code我使用来定义这些扩展方法:

This code either returns h.MetaData.GetExtendedName().Trim().ToLower() or it returns null if h, h.MetaData, or h.MetaData.GetExtendedName() is null. I've also extended this to check for null or empty strings, or null or empty collections. Here's code I use to define these extension methods:

public static class NullSafeExtensions
{
    /// <summary>
    /// Tests for null objects without re-computing values or assigning temporary variables.  Similar to 
    /// Groovy's "safe-dereference" operator .? which returns null if the object is null, and de-references
    /// if the object is not null.
    /// </summary>
    /// <typeparam name="TResult">resulting type of the expression</typeparam>
    /// <typeparam name="TCheck">type of object to check for null</typeparam>
    /// <param name="check">value to check for null</param>
    /// <param name="valueIfNotNull">delegate to compute if check is not null</param>
    /// <returns>null if check is null, the delegate's results otherwise</returns>
    public static TResult NullSafe<TCheck, TResult>(this TCheck check, Func<TCheck, TResult> valueIfNotNull)
        where TResult : class
        where TCheck : class
    {
        return check == null ? null : valueIfNotNull(check);
    }

    /// <summary>
    /// Tests for null/empty strings without re-computing values or assigning temporary variables
    /// </summary>
    /// <typeparam name="TResult">resulting type of the expression</typeparam>
    /// <param name="check">value to check for null</param>
    /// <param name="valueIfNotNullOrEmpty">delegate to compute non-null value</param>
    /// <returns>null if check is null, the delegate's results otherwise</returns>
    public static TResult CheckNullOrEmpty<TResult>(this string check, Func<string, TResult> valueIfNotNullOrEmpty)
        where TResult : class
    {
        return string.IsNullOrEmpty(check) ? null : valueIfNotNullOrEmpty(check);
    }
    /// <summary>
    /// Tests for null/empty collections without re-computing values or assigning temporary variables
    /// </summary>
    /// <typeparam name="TResult">resulting type of the expression</typeparam>
    /// <typeparam name="TCheck">type of collection or array to check</typeparam>
    /// <param name="check">value to check for null</param>
    /// <param name="valueIfNotNullOrEmpty">delegate to compute non-null value</param>
    /// <returns>null if check is null, the delegate's results otherwise</returns>
    public static TResult CheckNullOrEmpty<TCheck, TResult>(this TCheck check, Func<TCheck, TResult> valueIfNotNullOrEmpty)
        where TCheck : ICollection
        where TResult : class
    {
        return (check == null || check.Count == 0) ? null : valueIfNotNullOrEmpty(check);
    }
}

这篇关于如何有用的是C#的?运营商?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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