任意のタイプの配列の最大値を得るための委任と汎用メソッド実装

9770 ワード

委託方式実現:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace  
{
    class Program
    {
        delegate int CompareDelegate(object o1,object o2);

        static void Main(string[] args)
        {
            object[] array = new object[] {33,22,55,77,11};
            object max = GetMax(array,CompareInt);
            Console.WriteLine(max);

            object maxStr = GetMax(new object[] { "c", "bbbb", "aa" }, CompareString);
            Console.WriteLine(maxStr);

            Console.ReadKey();
        }

        static int CompareInt(object o1, object o2)
        {
            int n1 = Convert.ToInt32(o1);
            int n2 = Convert.ToInt32(o2);

            return n1 - n2;
        }

        static int CompareString(object s1,object s2)
        {
            string str1 = s1.ToString();
            string str2 = s2.ToString();

            return str1.Length - str2.Length;
        }

        static Object GetMax(object[] array,CompareDelegate del)
        {
            object max = array[0];
            for (int i = 1; i < array.Length; i++)
            {
                if (del(max,array[i])<0)
                {
                    max = array[i];
                }
            }
            return max;
        }

    }
}

 
汎用メソッド実装:(推奨)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace _02 
{
    delegate int GetMaxDeletate<T>(T t1, T t2);

    class Program
    {
        static void Main(string[] args)
        {
            int maxInt = GetMax<int>(new int[] { 3, 55, 11, 77, 333, 27 }, CompareInt);
            Console.WriteLine(maxInt);

            Person[] persons = { 
                            new Person(){Name=" ",Age =18},
                            new Person(){Name= " ",Age= 55}
                            };

            Person maxPerson = GetMax<Person>(persons, ComparePerson);
            Console.WriteLine(maxPerson.Name);

            Console.ReadKey();
        }

        // 
        static int CompareInt(int i1, int i2)
        {
            return i1 - i2;
        }

        // Person 
        static int ComparePerson(Person p1, Person p2)
        {
            return p1.Age - p2.Age;
        }

        //T    
        static T GetMax<T>(T[] array, GetMaxDeletate<T> del)
        {
            T max = array[0];

            for (int i = 1; i < array.Length; i++)
            {
                if (del(max, array[i]) < 0)
                {
                    max = array[i];
                }
            }
            return max;
        }
    }

    class Person
    {
        public string Name { get; set; }

        public int Age { get; set; }

    }
}