相关疑难解决方法(0)

奇数返回语法语句

我知道这可能听起来很奇怪,但我甚至不知道如何在互联网上搜索这种语法,我也不确定究竟是什么意思.

所以我看了一些MoreLINQ代码然后我注意到了这个方法

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这个奇怪的回报声明是什么?return _();

.net c# c#-7.0

102
推荐指数
2
解决办法
4546
查看次数

为什么要在 C# 中定义一个局部函数只是为了立即调用它(在 IEnumerable&lt;T&gt; 的上下文中)

我看了一下天才的MoreLINQ - 项目的几种扩展方法的实现。我遇到了一种我无法解释的风格习惯。也许你们中的一些人可以?

例如,它发生在Pairwise.cs 中,引用如下。

那么为什么作者会编写一个名为的本地函数_()来在返回表达式中调用它呢?仅仅在函数中实现yield return/不是很直接yield break吗?我怀疑它与编译器从 yield 实现生成 Enumerator 对象的方式有关。但我看不出有什么不同。事实上,甚至有一些封闭-ING发生的事情-我认为这是更糟糕的(!?)
编辑:不,它不应该被闭包,因为它不是一个lambda,但当地的功能,这将只是抓住外部范围变量为所欲为是。

    public static IEnumerable<TResult> Pairwise<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TSource, TResult> resultSelector)
    {
        if (source == null) throw new ArgumentNullException(nameof(source));
        if (resultSelector == null) throw new ArgumentNullException(nameof(resultSelector));

        return _(); IEnumerable<TResult> _()
        {
            using (var e = source.GetEnumerator())
            {
                if (!e.MoveNext())
                    yield break;

                var previous = e.Current;
                while (e.MoveNext())
                {
                    yield return resultSelector(previous, e.Current);
                    previous = e.Current;
                } …
Run Code Online (Sandbox Code Playgroud)

c# linq performance

3
推荐指数
1
解决办法
236
查看次数

标签 统计

c# ×2

.net ×1

c#-7.0 ×1

linq ×1

performance ×1