首页 > 代码库 > 委托案例1 可变的抽离出来

委托案例1 可变的抽离出来

namespace ChangeStringLib //公共类{    public class Class1    {        //public void ChangeString(string[] str)        //{        //    for (int i = 0; i < str.Length; i++)        //    {        //        str[i] = str[i].ToUpper();        //    }        //}        //公共的方法        public void ChangeString(string[] str, ChgStrDelegate chgStr)        {            for (int i = 0; i < str.Length; i++)            {                //委托,只是把方法中变的地方提取出来,便于写出通用的代码                str[i] = chgStr(str[i]);            }        }    }}

 委托类

namespace ChangeStringLib{    public delegate string ChgStrDelegate(string str);}

 

 

调用项

namespace ConsoleApplication1{    class Program    {        static void Main(string[] args)        {            ChangeStringLib.Class1 c1 = new ChangeStringLib.Class1();            string[] name = { "Bob", "Chris", "James", "Steve", "Jhoney" };            //把字符串都变成大写            //c1.ChangeString(name,ChangeStringToUpper);            c1.ChangeString(name, ChangeChangeAddWjx);            foreach (var item in name)            {                Console.WriteLine(item);            }            Console.WriteLine("ok");        }        static string ChangeChangeAddWjx(string msg)        {            return "★" + msg + "★";        }        static string ChangeStringToUpper(string msg)        {            return msg.ToUpper();        }    }}

 

委托案例1 可变的抽离出来