感受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 */