(C,VS2008)在我正在开发的一个程序中,我有很多对象都有一个ID并实现了IComparable,这样就可以通过ID轻松地搜索各种对象的列表-s。由于我讨厌复制/粘贴代码,我想我应该将这些功能抽象为一个基类,如下所示:using System;namespace MyProg.Logic{ abstract class IDObject : IComparable<IDObject> { private int miID; public int ID { get { return miID; } set { miID = value; } } public IDObject(int ID) { miID = ID; } #region IComparable<IDObject> Members int IComparable<IDObject>.CompareTo(IDObject other) { return miID.CompareTo(other.miID); } #endregion }}我看到的缺点是,使用.compareTo()可以直接比较两个各自继承它的单独类,我希望强制要求从idObject继承的每个类只能与同一类的其他类比较。所以我想知道怎么做using System;namespace MyProg.Logic{ abstract class IDObject : IComparable<T> where T : IDObject { private int miID; public int ID { get { return miID; } set { miID = value; } } public IDObject(int ID) { miID = ID; } #region IComparable<T> Members int IComparable<T>.CompareTo(T other) { return miID.CompareTo(other.miID); } #endregion }}但这会导致编译错误“非泛型声明不允许使用约束”看着它,我确信有一种方法可以做到这样,这样每个类只能与同一类的其他实例相比较,但是我无法理清语法。 (adsbygoogle = window.adsbygoogle || []).push({}); 最佳答案 您可以使用Curiously Recurring Template Pattern来解决此问题。abstract class Base<T> : IComparable<T> where T : Base<T> { public int Rank { get; set; } // Order instances of derived type T by Rank public int CompareTo(T other) { return Rank.CompareTo(other.Rank); }}class Foo : Base<Foo> {}class Bar : Base<Bar> {}static class Program { static void Main() { var foo1 = new Foo { Rank = 1 }; var foo2 = new Foo { Rank = 2 }; var bar1 = new Bar { Rank = 1 }; var bar2 = new Bar { Rank = 2 }; Console.WriteLine(foo1.CompareTo(foo2)); Console.WriteLine(bar2.CompareTo(bar1)); //error CS1503: Argument '1': cannot convert from 'Bar' to 'Foo' //Console.WriteLine(foo1.CompareTo(bar1)); }} (adsbygoogle = window.adsbygoogle || []).push({}); 08-04 23:38