zoukankan      html  css  js  c++  java
  • 感受C# 的魅力,将一坨代码写成一行

    摘自MSDN :https://msdn.microsoft.com/zh-cn/library/bb549151(v=vs.100).aspx

    1.平时定义一个委托

    using System;
    //声明委托
    delegate string ConvertMethod(string inString);
    
    public class DelegateExample
    {
       public static void Main()
       {
          // 用UppercaseString 方法实例化委托
          ConvertMethod convertMeth = UppercaseString;
          string name = "Dakota";
          // 调用委托
          Console.WriteLine(convertMeth(name));
       }
    
       private static string UppercaseString(string inputString)
       {
          return inputString.ToUpper();
       }
    }

    2. 泛型委托 Func<T,TResult> 出场

    备注: 还有个Action<T> 泛型委托,  和 Func<T,TResult> 的区别是前者没有返回值, 后者必须返回值  

    Action<T> : https://msdn.microsoft.com/zh-cn/library/018hxwa8(v=vs.100).aspx

     Func<T,TResult>  : https://msdn.microsoft.com/zh-cn/library/bb549151(v=vs.100).aspx

    using System;
    
    public class GenericFunc
    {
       public static void Main()
       {
          // 注意Func<string,string>,直接就声明了委托,不像刚才那么麻烦
          Func<string, string> convertMethod = UppercaseString;
          string name = "Dakota";
          // 调用委托
          Console.WriteLine(convertMethod(name));
       }
    
       private static string UppercaseString(string inputString)
       {
          return inputString.ToUpper();
       }
    }

    3.配合 匿名函数(这里用的lambda) 出场,一行代码搞定!!!

    using System;
    
    public class LambdaExpression
    {
       public static void Main()
       {
        //一行代码搞定!!! 左泛型委托,右函数实现 Func
    <string, string> convert = s => s.ToUpper(); string name = "Dakota";
        //调用委托 Console.WriteLine(convert(name)); } }

    4. 应用哈,将一个数组内的字母,全部转成大写

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    
    static class Func
    {
       static void Main(string[] args)
       {
          //一行代码,左泛型委托,右实现
          Func<string, string> selector = str => str.ToUpper();
    
          // 创建数组.
          string[] words = { "orange", "apple", "Article", "elephant" };
          // 将委托传入数组Select方法,实现转成大写
          IEnumerable<String> aWords = words.Select(selector);
    
          // 打印数组成员
          foreach (String word in aWords)
             Console.WriteLine(word);
       }
    }      
    /*
    最后输出:
    
       ORANGE
       APPLE
       ARTICLE
       ELEPHANT
    */
  • 相关阅读:
    Android开发 使用 adb logcat 显示 Android 日志
    【嵌入式开发】向开发板中烧写Linux系统-型号S3C6410
    C语言 结构体相关 函数 指针 数组
    C语言 命令行参数 函数指针 gdb调试
    C语言 指针数组 多维数组
    Ubuntu 基础操作 基础命令 热键 man手册使用 关机 重启等命令使用
    C语言 内存分配 地址 指针 数组 参数 实例解析
    CRT 环境变量注意事项
    hadoop 输出文件 key val 分隔符
    com.mysql.jdbc.exceptions.MySQLNonTransientConnectionException: Too many connections
  • 原文地址:https://www.cnblogs.com/anuo/p/5181443.html
Copyright © 2011-2022 走看看