【发布时间】:2014-12-09 15:30:40
【问题描述】:
我需要显式地实现标准 c# 接口,例如(IComparable、IComparer、IEquatable、IEnumerable、IEnumerator)。我做得对吗?
class Lemon : IComparable
{
public String name { get; set; }
public int id { get; set; }
public Lemon (String name, int id)
{
this.name = name;
this.id = id;
}
int IComparable.CompareTo(object obj)
{
Lemon other = (Lemon)obj;
if (this.id > other.id)
return 1;
else if (this.id < other.id)
return -1;
else return 0;
}
public void diamond ()
{
Console.WriteLine();
}
public override string ToString()
{
return this.name + " " + this.id;
}
}
现在是主要的:
static void Main(string[] args)
{
List<IComparable> icL = new List<IComparable>();
IComparable temp = new Lemon("Git", 99);
icL.Add(temp);
icL.Add(new Lemon("Green", 9));
icL.Add(new Lemon("Don", 7));
icL.Add(new Lemon("Simon", 12));
icL.Sort();
foreach (IComparable itm in icL)
{
Console.WriteLine(itm.ToString());
}
Console.WriteLine("----------");
}
那你怎么看?
另一个问题是当我遍历集合时如何访问方法 diamond ?
【问题讨论】:
-
实施 IComparable
与 IComparable 相对,可能值得一看。您的 CompareTo 方法将采用 Lemon 类型的参数,您可以简单地返回 id.CompareTo(other.Id) -
使实现
IEquatable的类型可变是非常危险的。您的代码还有其他一些非常奇特的事情;如果你告诉我们你是什么trying to accomplish 会有所帮助,而不仅仅是你在做什么,因为你在做什么毫无意义。 -
@DourHighArch 这只是一个例子,我正在制作其他项目,其要求之一是显式实现标准 .NET 接口之一
标签: c# .net oop interface explicit-interface