所以我在這個錯誤上畫空白。 無法比較數組中的兩個元素。 Array.Sort(patient);是錯誤產生的地方。我有一個IComparable接口,並用下面的代碼類文件:試圖通過病人ID號使用IComparable
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);
你有什麼錯誤?這聽起來不像標準.NET異常 – BradleyDotNET 2015-02-09 20:12:15
在mscorlib.dll中發生未處理的異常'System.InvalidOperationException' 附加信息:未能比較數組中的兩個元素。出現的錯誤是 – MeggMercer 2015-02-09 20:14:06
您不會在比較方法中處理NULL和對象而不是您的類。 – Dawnkeeper 2015-02-09 20:15:42