码迷,mamicode.com
首页 > Windows程序 > 详细

C#面向对象22 委托事件反射

时间:2018-06-13 15:01:59      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:定义   def   命名   面向   IV   匿名   write   space   ons   

1.委托的定义:声明委托类型(返回值和参数,命名空间中);定义委托对象

  (把委托想象成函数中的占位符~因为你并不确定调用哪个函数~)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace @delegate
{
    public delegate void DelSayHi(string name);
    class Program
    {
        static void Main(string[] args)
        {
            //1.委托的定义:声明委托类型(返回值和参数);定义委托对象;
            //DelSayHi del = SayChinese;
            //del("22");
            //DelSayHi del = delegate(string name){Console.WriteLine("吃了么?" + name);};
            //del("22");
            //DelSayHi del = (name) => { Console.WriteLine("吃了么?" + name); };
            //del("112233");
            
            //2
            Test("22", SayChinese);
            //3 匿名函数
            Test("222", delegate(string name) { Console.WriteLine("吃了么?" + name); });
            //4 lamda表达式
            Test("222", (name) => { Console.WriteLine("吃了么?" + name); });
            
            Console.ReadKey();
        }

        public static void Test(string name, DelSayHi del)
        {
            //调用
            del(name);
        }
        public static void SayChinese(string name)
        {
            Console.WriteLine("吃了么?" + name);
        }
        public static void SayEnglish(string name)
        {
            Console.WriteLine("Nice to meet you" + name);
        }

    }
}

 

2. 匿名函数 lamda表达式

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace delegate2
{
    public delegate string DelString(string name);
    class Program
    {
        static void Main(string[] args)
        {

            string[] names = { "abCDefG", "HIJKlmnOP", "QRsTuW", "XyZ" };

            //转大写 lamda
            DealString(names, (name) => { return name.ToUpper(); });
            //转大写 匿名函数
            DealString(names, delegate(string name) { return name.ToUpper(); });

            foreach (string  item in names)
            {
                Console.WriteLine(item);
            }
            Console.ReadKey();
        }

        static void DealString(string [] names ,DelString del2)
        {
            for (int i = 0; i < names.Length; i++)
            {
                names[i] = del2(names[i]);
            }
        }

    }
}

 

C#面向对象22 委托事件反射

标签:定义   def   命名   面向   IV   匿名   write   space   ons   

原文地址:https://www.cnblogs.com/youguess/p/9176881.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!