gpt4 book ai didi

c# - 使用 IComparable

转载 作者:行者123 更新时间:2023-11-30 22:00:36 24 4
gpt4 key购买 nike

所以我在这个错误上画了一个空白。无法比较数组中的两个元素。Array.Sort(患者);是产生错误的地方。我确实有一个 IComparable 接口(interface)和一个包含以下代码的类文件:Trying to sort by patient ID number

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;
}
}

这就是我的主要方法中的内容。没有添加 Display() 因为现在什么都没有添加,为什么它被注释掉了

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);

最佳答案

我想到了一些事情:

a) 为什么不实现 IComparable<Patient>

b) 为什么要重新实现 int.CompareTo(int) ?您的 IComparable 实现可能只返回 this.PatientID.CompareTo(other.PatientID) .

c) 您确定排序时数组已满吗?我不确定如果它包含 null 会发生什么.

关于c# - 使用 IComparable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28418413/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com