所以我在这个错误上画一个空白。未能比较数组中的两个元素。Array.Sort(病人);是错误产生的地方。我确实有一个IComparable接口和一个类文件,其代码如下:尝试按病人ID号进行排序
class Patient : IComparable
{
private int patientID;
private string patientName;
private int patientAge;
private decimal amount;
public int PatientId { get; set; }
public string PatientName { get; set; }
public int PatientAge { get; set; }
public decimal PatientAmount { get; set; }
int IComparable.CompareTo(Object o)
{
int value;
Patient temp = (Patient)o;
if (this.PatientId > temp.PatientId)
value = 1;
else if (this.PatientId < temp.PatientId)
value = -1;
else
value = 0;
return value;
}
}这就是我的主要方法。没有添加显示(),因为现在没有添加任何内容,为什么它被注释掉了
private static void Main(string[] args)
{
int numOfPatients =2 ;
Patient[] patient = new Patient[numOfPatients];
for (int x = 0; x < numOfPatients; x++)
{
int intvalue;
decimal dollarValue;
patient[x] = new Patient();
Console.Write("Patient {0}: ", (x + 1));
Console.WriteLine("Enter the Patients ID: ");
bool isNum = int.TryParse(Console.ReadLine(), out intvalue);
if (isNum)
{
patient[x].PatientId = intvalue;
}
else
{
Console.WriteLine("Patient ID was invalid. ID needs to be numbers");
Console.WriteLine("Enter the Patients ID: ");
int.TryParse(Console.ReadLine(), out intvalue);
}
Console.WriteLine("Enter the Patients Name: ");
patient[x].PatientName = Console.ReadLine();
Console.WriteLine("Enter the Patients Age: ");
bool isAge = int.TryParse(Console.ReadLine(), out intvalue);
if (isAge)
{
patient[x].PatientAge = intvalue;
}
else
{
Console.WriteLine("Patient Age was invalid. Age needs to be numbers");
Console.WriteLine("Enter the Patients Age: ");
int.TryParse(Console.ReadLine(), out intvalue);
}
Console.WriteLine("Enter the Patients Amount Due: ");
bool isAmount = Decimal.TryParse(Console.ReadLine(), out dollarValue);
if (isAmount)
{
patient[x].PatientAmount = dollarValue;
}
else
{
Console.WriteLine("Patient amount Due was invalid. Amount needs to be a numbers");
Console.WriteLine("Enter the Patients Amount Due: ");
int.TryParse(Console.ReadLine(), out intvalue);
}
}
Array.Sort(patient);
Console.WriteLine("Patients in order with Amounts Owed are: ");
for (int i = 0; i < patient.Length; ++i) ;
//Display(patient[i], numOfPatients);发布于 2015-02-09 20:20:17
我想到了几件事:
( a)为什么不实现IComparable<Patient>?
( b)为什么要重新实施int.CompareTo(int)?IComparable的实现可以只返回this.PatientID.CompareTo(other.PatientID)。
( c)在对数组进行排序时,您确定数组已满吗?我不知道如果它包含null会发生什么。
发布于 2015-02-09 20:16:30
我只会写
return this.PatientId.CompareTo(temp.PatientId)在overriden CompareTo方法中,类。不需要使用平等符号。这将为您执行int比较,并返回正确的值。
我还建议您只使用IList类的一些实现,然后可以使用LinQ语句。使用这将防止“数组”中出现空值。
发布于 2015-02-09 23:30:47
看起来,如果使用类型化数组传递Array.Sort,则会调用Array.Sort<T>(T[])重载。根据MSDN文档,这个重载使用IComparable<T>接口来比较对象。所以看起来你有两个选择:
IComparable<T>而不是IComparable (更好)。Array,以调用使用IComparable接口的Array.Sort(Array)重载(更糟)。https://stackoverflow.com/questions/28418413
复制相似问题