교재의 예제코드대로 delegate를 이용해서 다양한 타입을 받을 수 있는 범용 정렬코드를 작성하다가 문제가 생겼습니다.
분명 int도 System.ValueType을 상속받았고 System.ValueType은 object를 상속받았으니 형변환이 될텐데, 단일 변수의 경우는 되지만 배열의 경우에는 안됩니다.
AscSortByNumber함수의 내용처럼 단일 변수일 경우에는 형변환이 되는데 배열일 때는 안되는 이유를 모르겠습니다.
1)안되는 이유와
2)해결방법
이 있다면 해결방법도 알고싶습니다.
아래의 코드는 교재의 예제코드를 숫자값들도 정렬할 수 있게끔 제가 마저 작성한 코드이며
이슈되는 코드들 위에 주석을 달았습니다.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApp3
{
delegate bool CompareDelegate(object arg1, object arg2);
class SortObject
{
object[] things;
//object[]가 int[]는 받을 수가 없습니다.
public SortObject(object[] things)
{
this.things = things;
}
public void Sort(CompareDelegate compareMethod)
{
object temp;
for (int i = 0; i < things.Length; i++)
{
int lowPos = i;
for (int j = i + 1; j < things.Length; j++)
{
if (compareMethod(things[j], things[lowPos]))
{
lowPos = j;
}
}
temp = things[lowPos];
things[lowPos] = things[i];
things[i] = temp;
}
}
public void Display()
{
for (int i = 0; i < things.Length; i++)
{
Console.WriteLine(things[i] + ", ");
}
}
}
class Person
{
public int Age;
public string Name;
public Person(int age, string name)
{
this.Age = age;
this.Name = name;
}
public override string ToString()
{
return Name + ": " + Age;
}
}
class Program
{
static bool AscSortByName(object arg1, object arg2)
{
Person person1 = arg1 as Person;
Person person2 = arg2 as Person;
return person1.Name.CompareTo(person2.Name) < 0;
}
static bool AscSortByNumber(object arg1, object arg2)
{
//이처럼 배열이 아닌 경우에는 잘됩니다.
int number1 = (int)arg1;
int number2 = (int)arg2;
return number1 < number2;
}
static void Main(string[] args)
{
Person[] people = new Person[] { new Person(30, "홍길동"), new Person(17, "김삿갓"), new Person(24, "가나연") };
SortObject sortPerson = new SortObject(people);
sortPerson.Sort(AscSortByName);
sortPerson.Display();
Console.WriteLine();
int[] intArray = new int[] { 5, 2, 3, 1, 0, 4 };
//int[]를 object[]로 변환할 수 없습니다.
//(object[])intArray, intArray as object[] 모두 안됩니다.
SortObject sortNumber = new SortObject(intArray);
sortNumber.Sort(AscSortByNumber);
sortNumber.Display();
}
}
}
[최초 등록일: ]
[최종 수정일: 3/10/2018]