奇数返回语法语句

2024-03-17

我知道这可能听起来很奇怪,但我什至不知道如何在互联网上搜索这个语法,而且我也不确定到底是什么意思。

所以我看了一些 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;
        }
    }
}

这个奇怪的 return 语句是什么?return _(); ?


这是支持本地函数的C# 7.0....

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

        // This is basically executing _LocalFunction()
        return _LocalFunction(); 

        // This is a new inline method, 
        // return within this is only within scope of
        // this method
        IEnumerable<TSource> _LocalFunction()
        {
            var knownKeys = new HashSet<TKey>(comparer);
            foreach (var element in source)
            {
                if (knownKeys.Add(keySelector(element)))
                    yield return element;
            }
        }
    }

当前的 C# 具有Func<T>

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

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

        // This is basically executing func
        return func(); 

    }

诀窍是, _() 在使用后声明,这完全没问题。

本地函数的实际使用

上面的示例只是演示了如何使用内联方法,但很可能如果您只调用一次方法,那么它是没有用的。

但在上面的例子中,正如评论中提到的Phoshi and Luaan,使用局部函数有一个优点。由于除非有人迭代它,否则带有yield return的函数不会被执行,在这种情况下,即使没有人迭代该值,本地函数外部的方法也会被执行,并且参数验证也会被执行。

很多时候我们在方法中都有重复的代码,让我们看看这个例子..

  public void ValidateCustomer(Customer customer){

      if( string.IsNullOrEmpty( customer.FirstName )){
           string error = "Firstname cannot be empty";
           customer.ValidationErrors.Add(error);
           ErrorLogger.Log(error);
           throw new ValidationError(error);
      }

      if( string.IsNullOrEmpty( customer.LastName )){
           string error = "Lastname cannot be empty";
           customer.ValidationErrors.Add(error);
           ErrorLogger.Log(error);
           throw new ValidationError(error);
      }

      ... on  and on... 
  }

我可以优化这个...

  public void ValidateCustomer(Customer customer){

      void _validate(string value, string error){
           if(!string.IsNullOrWhitespace(value)){

              // i can easily reference customer here
              customer.ValidationErrors.Add(error);

              ErrorLogger.Log(error);
              throw new ValidationError(error);                   
           }
      }

      _validate(customer.FirstName, "Firstname cannot be empty");
      _validate(customer.LastName, "Lastname cannot be empty");
      ... on  and on... 
  }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

奇数返回语法语句 的相关文章

随机推荐

  • WCF发送大量数据

    我想将大量数据发送到 WCF 服务 数据可能由数千个 od 记录 实体 组成 具体取决于解析的输入文件 现在的问题是 发送这些数据的最佳方式是什么 A 逐条记录 通过这个 我将确保我不会超过允许的最大消息大小 并且我可以从 las 成功发送
  • pandas.read_clipboard 来自云托管的 jupyter?

    我正在服务器上运行 JupyterHub 的 Data8 实例 并运行 JupyterLabpd read clipboard 似乎不起作用 我在谷歌colab中看到同样的问题 import pandas as pd pd read cli
  • 具有固定不均匀行的 HTML 表格

    I m creating a page that allows the user to select a time slot from a schedule I would prefer to do this with some sort
  • PhoneRTC 64 位支持吗?

    PhoneRTC http phonertc io 目前不支持 64 位设备 从2015年2月1日起 Apple 要求所有 iOS 应用程序支持 64 位设备 https developer apple com news id 102020
  • 最严格的 C 代码的 GCC 选项? [复制]

    这个问题在这里已经有答案了 应该设置哪些 GCC 选项以使 GCC 尽可能严格 我的意思是尽可能严格 我正在用 C89 编写并希望我的代码符合 ANSI ISO 兼容 我建议使用 Wall Wextra std c89 pedantic W
  • 如何在属性选择器中使用/模拟类似正则表达式的反向引用?

    我想要做的是编写一个在一个地方匹配任意值的选择器 然后要求一个不同的值与其相等 如果 attr value 将 值 解析为正则表达式 那么这将解决我的问题 class class if 1 styles 显然 我可以单独列出每个可能的类 但
  • Docker nginx/traefik 301 将 http 重定向到本地主机上的 https

    这是后续关闭 Docker 中的 https https stackoverflow com questions 67087945 turn off https in docker还有一些更多信息 我还没想明白 我在 Docker slac
  • 如何使用 window.fetch 下载文件?

    如果我想下载一个文件 我应该在then下面块 function downloadFile token fileId let url https www googleapis com drive v2 files fileId alt med
  • 如何开始使用 memcached

    目前我正在做一个项目 需要使用memcached 我研究了很多网络链接 但我不明白如何开始使用 memcached 我已经使用过 mongodb 但希望获得有关 memcached 配置的帮助 我使用的是 Windows 7 操作系统 到目
  • FXCop 选角警告

    运行 FXCop 时出现以下错误 CA1800 微软 性能 obj 一个变量 被转换为类型 方法中多次 Job ProductsController Details int int 缓存 as 的结果 运算符或直接强制转换以便 消除多余的c
  • 服务器代码中的 Webpack 热模块替换

    到目前为止 我看过的所有 webpack 示例都涉及客户端热模块替换 例如 this http andrewhfarmer com webpack hmr tutorial and this https github com glenjam
  • 带有闪亮的 R Leaflet 中的图标未加载(空图像)

    R 3 4 3 64 位 RStudio shinydashboard 0 6 1 shiny 1 0 5 leaflet extras 0 2 Chrome 我正在制作在 R Leaflet 中使用 Shiny 的图标 我得到的所有内容如
  • Angular 8 如何从 ngOnInit 中的可观察值获取价值以及它们的行为方式[重复]

    这个问题在这里已经有答案了 你好社区 我正在尝试使用 HttpClient 模块从我的 api 获取一些数据 api 调用是在我的服务中定义的 我在组件中的 Lifecyclehooks 中调用它们 但我很难理解返回的可观察量的行为以及如何
  • 关于 select_list 和重新加载的 Watir 问题

    我有一个包含多个选项的下拉菜单 每当您选择一个选项时 页面都会重新加载该选项的特定数据 目前我正在使用 select list name strg set value 它很好地完成了这部分工作 但它不会使用特定数据重新加载页面 任何人都知道
  • 为 Express 和 Nginx 配置 HTTPS

    我正在尝试配置我的 ExpressJS 应用程序以进行 https 连接 Express 服务器运行在 localhost 8080 安全服务器运行在 localhost 8443 以下是与 https 相关的 server js 代码 v
  • 如何使用 Azure API 管理链接 API

    如何使用 Azure API 管理在同一 URL 上链接多个 API 我有两个 API 用户存储和用户资源 api 我想构建rest api 以便资源与用户相关 我的公司 用户 电子邮件受保护 cdn cgi l email protect
  • Nodejs 模块“worker_threads”返回错误“错误:此 Node 实例使用的 V8 平台不支持创建 Workers”

    我正在创建一个应用程序 我需要停止一些代码 而不需要执行所有有问题的永远睡眠方法 或者在每个函数中创建一个 if 语句检查 stop 变量是否为真 所以我决定使用worker threads 但每次我使用它 我收到一个错误 错误 此 Nod
  • 每秒更新一次 React 组件

    我一直在玩 React 并有以下仅渲染的时间组件Date now 到屏幕 import React Component from react class TimeComponent extends Component constructor
  • C# 中的 System.FormatException

    在我尝试为 sale 变量分配值的行中的每种情况下 我不断收到 FormatException 有人知道我做错了什么吗 我应该将此控制台程序作为学习循环的作业 但我正在了解更多有关其他内容的信息 它应该根据每笔销售的 10 佣金来记录销售人
  • 奇数返回语法语句

    我知道这可能听起来很奇怪 但我什至不知道如何在互联网上搜索这个语法 而且我也不确定到底是什么意思 所以我看了一些 MoreLINQ 代码 然后我注意到了这个方法 public static IEnumerable