zoukankan      html  css  js  c++  java
  • .NET中的Func委托用法

    MSDN对于Func<T, TResult>)的官方解释:
    封装一个具有一个参数并返回 TResult 参数指定的类型值的方法。 

    下面通过几个例子对比下,就容易知道其用法:

    以下例子演示了如何利用委托将字符串转化为大写:

        delegate string ConvertMethod(string inString);

        private static string UppercaseString(string inputString)
        {
            return inputString.ToUpper();
        }

        protected void Page_Load(object sender, EventArgs e)
        {       
            //ConvertMethod convertMeth = UppercaseString; 也可以这样写
            ConvertMethod convertMeth = new ConvertMethod(ppercaseString);
            string name = "Dakota";
            Response.Write(convertMeth(name));//通过委托调用UppercaseString方法
        }

       
    这段代码很容易理解,定义一个方法UppercaseString,功能很简单:将字符串转化为大写,然后定义一个ConvertMethod的实例来调用这个方法,最后将Dakota转化为大写输出


    接下来改进一下,将Page_Load中的 ConvertMethod convertMeth = new ConvertMethod(ppercaseString)改为Func 泛型委托,即:

      protected void Page_Load(object sender, EventArgs e)
        {
            Func<string, string> convertMeth = UppercaseString;
            string name = "Dakota";
            Response.Write(convertMeth(name));  

        }


       
     运行后,与前一种写法结果完全相同,这里再联系官方解释想一想,Func<string, string>即为封闭一个string类型的参数,并返回string类型值的方法

    当然,我们还可以利用匿名委托,将这段代码写得更简洁:

    protected void Page_Load(object sender, EventArgs e)
        {
            Func<string, string> convertMeth = delegate(string s) { return s.ToUpper(); };
            string name = "Dakota";
            Response.Write(convertMeth(name));
        } 

       
    怎么样?是不是清爽很多了,但这并不是最简洁的写法,如果利用Lambda表达式,还可以再简化:

    protected void Page_Load(object sender, EventArgs e)
        {
            Func<string, string> convertMeth = s => s.ToUpper();
            string name = "Dakota";
            Response.Write(convertMeth(name));
        }

       
    现在应该体会到什么叫“代码的优雅和简洁”了吧? 记起了曾经学delphi时,一位牛人的预言:以后可能会出现一种新学科:程序美学! 对此,我深信不疑:优秀的代码就是一种美!

    在linq to sql中其实大量使用了Func<T, TResult>这一泛型委托,下面的例子是不是会觉得很熟悉:

    protected void Page_Load(object sender, EventArgs e)
        {
            Func<string, string> convertMeth = str => str.ToUpper();        
            string[] words = { "orange", "apple", "Article", "elephant" };        
            IEnumerable<String> aWords = words.Select(convertMeth);
            foreach (String s in aWords)
            {
                Response.Write(s + "<br/>");
            }

        }

    原文链接:http://www.cnblogs.com/lin614/archive/2008/08/07/1262491.html

  • 相关阅读:
    spring cloud 和 阿里微服务spring cloud Alibaba
    为WPF中的ContentControl设置背景色
    java RSA 解密
    java OA系统 自定义表单 流程审批 电子印章 手写文字识别 电子签名 即时通讯
    Hystrix 配置参数全解析
    spring cloud 2020 gateway 报错503
    Spring Boot 配置 Quartz 定时任务
    Mybatis 整合 ehcache缓存
    Springboot 整合阿里数据库连接池 druid
    java OA系统 自定义表单 流程审批 电子印章 手写文字识别 电子签名 即时通讯
  • 原文地址:https://www.cnblogs.com/yasin/p/3620341.html
Copyright © 2011-2022 走看看