码迷,mamicode.com
首页 > 其他好文 > 详细

C#—委托分析

时间:2014-06-03 09:04:42      阅读:266      评论:0      收藏:0      [点我收藏+]

标签:c   style   class   blog   code   java   

1.简单委托示例

bubuko.com,布布扣
bubuko.com,布布扣
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SimpleTest
{
    class Program
    {
        private delegate string GetAString();  //声明委托
        static void Main(string[] args)
        {
            int x = 40;
            GetAString delegateString = new GetAString(x.ToString); //委托接受一个参数的构造函数
            GetAString delegateString1 = x.ToString;  //将方法的地址赋值给委托变量 Tostring()是字符串对象
            Console.WriteLine("string is {0}",delegateString());
            Console.WriteLine("string1 is {0}", delegateString1());
        }
    }
}
View Code
bubuko.com,布布扣

输出结果

bubuko.com,布布扣

2.委托数组实现多播委托(调用多个方法) 包括func<T>委托方式

操作类(MathOperation)

bubuko.com,布布扣
bubuko.com,布布扣
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SimpleTest1
{
    class MathOperation
    {
        public static double MultiplyByTwo(double value)
        {
            return value * 2;
        }

        public static double Square(double value)
        {
            return value * value;
        }
    }
}
View Code
bubuko.com,布布扣

测试类

bubuko.com,布布扣
bubuko.com,布布扣
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SimpleTest1
{
    class Program
    {
        delegate double DoubleOP(double value);  //声明委托

        //将委托传递给方法
        //委托作为第一个参数传递
        private static void ProcessAndDisplayNumber(DoubleOP action,double value)
        {
            double result = action(value);  // 
            Console.WriteLine("Value is {0},result of operation is {1}",value,result);
        }

        //利用Func<T>泛型实现委托
        private static void ProcessAndDisplayNumber(Func<double, double> action, double value)
        {
            double result = action(value);
            Console.WriteLine("Value is {0},result of operation is {1}", value, result);
        }

        static void Main(string[] args)
        {
            //方式一
            //DoubleOP[] operations =  // 实例化一个委托的数组,可以在循环中调用不同的方法
            //{
            //    MathOperation.MultiplyByTwo,
            //    MathOperation.Square
            //};   
            
            //方式二
            Func<double, double>[] operations =   //Func<T>允许调用带返回类型的方法
            {
                MathOperation.MultiplyByTwo,
                MathOperation.Square
            };


            /*
             * i=0的时候,即operations[0]委托的实例为 MathOperation.MultiplyByTwo,
             * 调用ProcessAndDisplayNumber(operations[0],2.0)后 
             * double result = action(value);  // action(value)相当于调用MathOperation.MultiplyByTwo(value)
             * operations[i] 委托表示的方法,operations[i](2.0) 调用委托的商品
             */
            for (int i = 0; i < operations.Length; i++)
            {
                Console.WriteLine("Using operations [{0}]:", i);
                ProcessAndDisplayNumber(operations[i], 2.0);
                ProcessAndDisplayNumber(operations[i], 7.84);
                ProcessAndDisplayNumber(operations[i], 1.414);
                Console.WriteLine();
            }

         

          
        }
    }
}
View Code
bubuko.com,布布扣

输出结果

bubuko.com,布布扣

3.Action<T>实现多播委托改上上述测试样例

操作类(MathOperation)

bubuko.com,布布扣
bubuko.com,布布扣
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Multicastdelegate
{
    class MathOperations
    {
        public static void MultiplyByTwo(double value)
        {
            double result = value * 2;
            Console.WriteLine("[{0}]Multiply by 2 = [{1}]:",value,result);
        }

        public static void Square(double value)
        {
            double result = value * value;
            Console.WriteLine("[{0}]Square = [{1}]",value,result);
        }
    }
}
View Code
bubuko.com,布布扣

测试类:

bubuko.com,布布扣
bubuko.com,布布扣
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Multicastdelegate
{
    class Program
    {
        /// <summary>
        /// 多播委托方式
        /// </summary>
        /// <param name="action"></param>
        /// <param name="value"></param>
        public static void ProcessAndDisplayNumber(Action<double> action,double value)
        {
            Console.WriteLine("ProcessAndDisplayNumber called with value={0}",value);
            action(value);
        }

        static void Main(string[] args)
        {
            Action<double> operations = MathOperations.MultiplyByTwo;
            operations+= MathOperations.Square;  //+=向委托中添加方法

            ProcessAndDisplayNumber(operations,2.0);
            ProcessAndDisplayNumber(operations, 4.0);
        }
    }
}
View Code
bubuko.com,布布扣

输出结果:

bubuko.com,布布扣

4.对象排序的委托(冒泡排序)

冒泡算法类(BubbleSorter)

bubuko.com,布布扣
bubuko.com,布布扣
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BubbleSort
{
    /// <summary>
    /// 冒泡排序
    /// </summary>
    class BubbleSorter
    {
        /// <summary>
        /// comparison必须引用一个方法,该方法带有两个参数,如果第一个参数“小于”第二个参数返回true
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sortArray"></param>
        /// <param name="comparison"></param>
        static public void Sort<T>(IList<T> sortArray, Func<T, T, bool> comparison)
        {
            bool swapped = true;
            do
            {
                swapped = false;
                for (int i = 0; i < sortArray.Count - 1; i++)
                {
                    if (comparison(sortArray[i + 1], sortArray[i]))
                    {
                        T temp = sortArray[i];
                        sortArray[i] = sortArray[i + 1];
                        sortArray[i + 1] = temp;
                        swapped = true;
                    }
                }
            } while (swapped);
        }
    }
}
View Code
bubuko.com,布布扣

职工信息类(Employee)

bubuko.com,布布扣
bubuko.com,布布扣
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BubbleSort
{
    class Employee
    {
        public string Name { get; set; }
        public decimal Salary { get; set; }
        public override string ToString()
        {
            return string.Format("{0},{1:C}", Name, Salary);
        }

        public Employee(string name, decimal salary)
        {
            this.Name = name;
            this.Salary = salary;
        }

        /// <summary>
        /// 为了匹配冒泡排序的Func<T, T, bool> comparison必须定义如下方法
        /// </summary>
        /// <param name="e1"></param>
        /// <param name="e2"></param>
        /// <returns></returns>
        public static bool CompareSalary(Employee e1, Employee e2)
        {
            return e1.Salary < e2.Salary;
        }
    }

}
View Code
bubuko.com,布布扣

测试类

bubuko.com,布布扣
bubuko.com,布布扣
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BubbleSort
{
    class Program
    {
        static void Main(string[] args)
        {
            Employee[] employees =
            {
                new Employee("小张", 2000),
                new Employee("小王", 3000),
                new Employee("小李", 4000),
                new Employee("小赵", 2500)
            };

            BubbleSorter.Sort(employees, Employee.CompareSalary); //利用委托对对象排序

            foreach (var employee in employees)
            {
                Console.WriteLine(employee);
            }

        }
    }
}
View Code
bubuko.com,布布扣

输出结果:

bubuko.com,布布扣

 

C#—委托分析,布布扣,bubuko.com

C#—委托分析

标签:c   style   class   blog   code   java   

原文地址:http://www.cnblogs.com/zxd543/p/3760547.html

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