语法的含义:return _();IEnumerable< TSource>_() [英] Meaning of the syntax: return _(); IEnumerable<TSource> _()

查看:68
本文介绍了语法的含义:return _();IEnumerable< TSource>_()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的C#代码中,我发现 _()的用法很奇怪.谁能解释这是什么意思?

In the C# code below, I found the usage of _() strange. Can anyone explain what this means?

public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source,
            Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)
{
    if (source == null) throw new ArgumentNullException(nameof(source));
    if (keySelector == null) throw new ArgumentNullException(nameof(keySelector));

    return _(); IEnumerable<TSource> _()
    {
        var knownKeys = new HashSet<TKey>(comparer);
        foreach (var element in source)
        {
            if (knownKeys.Add(keySelector(element)))
                yield return element;
        }
    }
}

推荐答案

通过在 return 语句后插入换行符,可以更容易地理解代码:

The code might be more easily understood by inserting a line break after the return statement:

return _();

IEnumerable<TSource> _()
{
    var knownKeys = new HashSet<TKey>(comparer);
    foreach (var element in source)
    {
        if (knownKeys.Add(keySelector(element)))
            yield return element;
    }
}

在这种情况下,下划线只是

In this context, the underscore is just an arbitrary name for a local function (which is a new feature introduced in C# 7.0). If you prefer, you could replace the underscore by a more descriptive name:

return DistinctByHelper();

IEnumerable<TSource> DistinctByHelper()
{
    var knownKeys = new HashSet<TKey>(comparer);
    foreach (var element in source)
    {
        if (knownKeys.Add(keySelector(element)))
            yield return element;
    }
}

作为本地函数,_(或DistinctByHelper)方法可以访问 DistinctBy 方法的所有变量.

As a local function, the _ (or DistinctByHelper) method can access all the variables of the DistinctBy method.

顺便说一下,这里有两个方法的原因是,如果任何参数为null,则在调用 DistinctBy 而不是调用 DistinctBy 时会立即引发 ArgumentNullException 枚举结果时(由于 yield return 语句的存在).

By the way, the reason for having two methods here is so that, in case any argument is null, ArgumentNullException will be thrown immediately when DistinctBy is called instead of when the result is enumerated (due to the presence of the yield return statement).

这篇关于语法的含义:return _();IEnumerable&lt; TSource&gt;_()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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