我试图用最佳结果的俱乐部对列表进行排序,我必须使用排序方法,但是它显示错误,我在做错了什么。我知道这是一个排序方法的问题,但找不到错误,我使它与lambda表达式一起使用,但我想用Sort方法来做;
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
// class with objects
Club barca = new Club("Barcelona", 1900, 100, 20);
Club Real = new Club("Real", 1910, 80, 70);
Club Manchester = new Club("Manchester", 1890, 75, 55);
Club Milan = new Club("Milan", 1880, 45, 65);
//new list of clubs
var myclublist = new List<IClub>();
///add clubs in list
myclublist.Add(barca);
myclublist.Add(Real);
myclublist.Add(Manchester);
myclublist.Add(Milan);
// sort method for list
myclublist.Sort();
//show clubs name with best results
foreach (var item in myclublist)
{
if (item.IsPositiveBallRatio() == true)
{
Console.WriteLine(item.ClubName());
}
}
}
// club class
public class Club : IClub, IComparable<Club>
{
public string Name { get; set; }
public int Year { get; set; }
public int Scoredgoals { get; set; }
public int Lossgoals { get; set; }
public Club(string name, int year, int scoredgoals, int lossgoals)
{
Name = name;
Year = year;
Scoredgoals = scoredgoals;
Lossgoals = lossgoals;
}
public int BallRatio()
{
int ratio;
ratio = Scoredgoals - Lossgoals;
return ratio;
}
public bool IsPositiveBallRatio()
{
if (Scoredgoals > Lossgoals)
{
return true;
}
else
return false;
}
public string ClubName()
{
string n;
n = Name;
return n;
}
public int CompareTo(Club other)
{
return BallRatio().CompareTo(other.BallRatio());
}
}
// inferface for club class
interface IClub
{
int BallRatio();
bool IsPositiveBallRatio();
string ClubName();
}
}
我做错了什么?
为什么: IClub
与自身不可媲美,并且在运行时间以for Generic方法的代码可用的类型没有其他信息。因此,它回到了IComparable
的非生成版本的Club
类型。
修复:
- 使用
Club
的列表而不是List<IClub>
的列表,因为Club
与自身相媲美 在
Club
上实现非生成IComparable
:public class Club : IClub, IComparable<Club> , IComparable { ... public int CompareTo(object obj) { return CompareTo(obj as Club); } }
使您在列表中拥有的类型(
IClub
(与自身相媲美-IClub : IComparable<IClub>
如果您真的期望在数组中使用混合的IClub
实现,则可以解决问题:public class Club : IClub, IComparable<Club> { ... public int CompareTo(IClub other) { return CompareTo(other as Club); } } public interface IClub : IComparable<IClub> {...}
有关详细信息,请参见列表。
注意:这篇文章中的CompareTo
是示例,您需要添加所有类型/NULL检查以使其在真实代码中工作。