C#での委任の使用
15132 ワード
1、依頼呼び出し方法
- class MathOperations
- {
- public static double MultiplyByTwo(double value)
- {
- return value * 2;
- }
- public static double Square(double value)
- {
- return value * value;
- }
- }
- /// <summary>
- ///
- /// </summary>
- /// <param name="x"></param>
- /// <returns></returns>
- delegate double DoubleOp(double x);
-
- class Program
- {
- static void Main(string[] args)
- {
- // ,
- DoubleOp[] operations = {
- new DoubleOp(MathOperations.MultiplyByTwo),
- new DoubleOp(MathOperations.Square),
- };
- for (int i = 0; i < operations.Length; i++)
- {
- Console.WriteLine("Using opertion[{0}]",i);
- ProcessAndDisplayNumber(operations[i],2.0);
- ProcessAndDisplayNumber(operations[i], 7.94);
- ProcessAndDisplayNumber(operations[i],1.414);
- Console.ReadLine();
- }
- }
-
- /// <summary>
- /// ( )
- /// </summary>
- /// MultiplyByTwo
- /// <param name="action"></param>
- /// <param name="value"></param>
- static void ProcessAndDisplayNumber(DoubleOp action,double value)
- {
- double result = action(value);
- Console.WriteLine("Value is {0}, {1}",value,result);
- }
- }
2、実現を依頼する泡立ちソート
- class Program
- {
- /// <summary>
- /// ,
- /// </summary>
- public delegate bool CompareOp(object lhs, object rhs);
-
- static void Main(string[] args)
- {
- Employee[] emlpoyees = {
- new Employee("A",20000),
- new Employee("B",10000),
- new Employee("C",25000),
- new Employee("D",18000)
- };
- CompareOp employeeCompareOp = new CompareOp(Employee.RhsIsGreater);
- //
- BubbleSorter.Sort(emlpoyees,employeeCompareOp);
-
- for (int i = 0; i < emlpoyees.Length; i++)
- {
- Console.WriteLine(emlpoyees[i].ToString());
- }
- Console.ReadLine();
- }
- }
-
- /// <summary>
- ///
- ///
- /// </summary>
- class BubbleSorter
- {
- /// <summary>
- /// RhsIsGreater
- /// </summary>
-
- public static void Sort(object[] sortArray, Program.CompareOp gtMethod)
- {
- for (int i = 0; i < sortArray.Length; i++)
- {
- for (int j = i + 1; j < sortArray.Length; j++)
- {
- if (gtMethod(sortArray[i], sortArray[j]))
- {
- object temp = sortArray[i];
- sortArray[i] = sortArray[j];
- sortArray[j] = temp;
- }
- }
- }
- }
- }
- class Employee
- {
- public string strName;
- public decimal strSalary;
- public Employee(string strName, decimal strSalary)
- {
- this.strName = strName;
- this.strSalary = strSalary;
- }
-
- public override string ToString()
- {
- return string.Format(strName + ":{0:C}", strSalary);
- }
-
- /// <summary>
- /// true
- /// </summary>
- /// <param name="lhs"></param>
- /// <param name="rhs"></param>
- /// <returns></returns>
- public static bool RhsIsGreater(object lhs, object rhs)
- {
- Employee empLhs = (Employee)lhs;
- Employee empRhs = (Employee)rhs;
- return (empLhs.strSalary > empRhs.strSalary) ? true : false;
- }
- }