【发布时间】:2019-01-05 06:11:30
【问题描述】:
我正在尝试比较属于不同类的两个不同对象并使用IComparable 接口对它们进行排序。请在下面找到我的代码以及我可以改进的地方 我已经理解错误但不知道如何修复它。
public class Program : IComparable
{
public static void Main(string[] args)
{
var newList = new List<Object>();
newList.Add(new Program { carName = "mercedes benz", topSpeed = 160 });
newList.Add(new SecondClass { carName = "BMW", topSpeed = 140 });
newList.Sort();
foreach (var list in newList)
{
Console.WriteLine(list.carName + " " + list.topSpeed);
/* Getting an error on this line stating 'object' does not contain a definition for 'carName' and no extension method 'carName' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)*/
}
}
public string carName { get; set; }
public int topSpeed { get; set; }
public int CompareTo(Object obj)
{
Program classObject = (Program)obj;
if (this.topSpeed > classObject.topSpeed)
return 1;
else if (this.topSpeed == classObject.topSpeed)
return 0;
else return -1;
}
}
public class SecondClass
{
public string carName { get; set; }
public int topSpeed { get; set; }
}
/* Edit: implemented abstract class however I am getting this "Unhandled Exception Message": System.InvalidCastException: Unable to cast object of type 'CSharpbasics.SecondClass' to type 'CSharpbasics.Program'.*/
public class SecondClass : Car { }
public abstract class Car : IComparable
{
public string carName { get; set; }
public int topSpeed { get; set; }
public int CompareTo(Object obj)
{
Program classObject = (Program)obj;
if (this.topSpeed > classObject.topSpeed)
return 1;
else if (this.topSpeed == classObject.topSpeed)
return 0;
else return -1;
}
}
public class Program : Car
{
static void Main(string[] args)
{
var newList = new List<Car>();
newList.Add(new Program { carName = "Wagon R", topSpeed = 160 });
newList.Add(new SecondClass { carName = "Swift", topSpeed = 140 });
newList.Sort();
foreach (var list in newList)
Console.WriteLine($"{list.carName} {list.topSpeed});
}
}
【问题讨论】:
-
你有很多重复的代码。你真的应该考虑改变你的设计,不要重复相同的代码两次。
标签: c# interface icomparable