带有generics的C#boxing枚举错误

我不明白这里发生了什么……

我有以下错误: 类型'TestApp.TestVal'不能用作generics类型或方法'TestApp.SomeClass'中的类型参数'T' 'TestApp.SomeClass' 没有从'TestApp.TestVal''System.IComparable'装箱转换。

以下代码发生此错误:

 public enum TestVal { First, Second, Third } public class SomeClass where T : IComparable { public T Stored { get { return storedval; } set { storedval = value; } } private T storedval; } class Program { static void Main(string[] args) { //Error is on the next line SomeClass t = new SomeClass(); } } 

由于枚举是默认的int而且int实现了IComparable接口,所以看起来应该没有错误….

首先,我不确定将IComparable与枚举使用是否明智…… IEquatable ,当然 – 但比较一下?

作为一种更安全的替代品; 而不是使用generics约束IComparable ,也许在类中使用Comparer.Default 。 这具有支持IComparableIComparable的优点 – 这意味着您传播的约束较少。

例如:

 public class SomeClass { // note no constraint public int ExampleCompareTo(T other) { return Comparer.Default.Compare(Stored, other); } ... [snip] } 

这适用于枚举:

 SomeClass t = new SomeClass(); t.Stored = TestVal.First; int i = t.ExampleCompareTo(TestVal.Second); // -1 

枚举不是从System.Int32s派生的 – 它们派生自System.Enum,它没有实现IComparable (它确实实现了IComparable )。

虽然默认情况下枚举的基础值是int,但枚举本身不是。 因此,两者之间没有转换。

在C#中,枚举实现IComparable ,但不是通用的IComparable 。 我不确定为什么会这样,但也许你可以在where子句中切换到非genericsIComparable

Enum没有实现IComparable ,但它确实实现了IComparable 。 因此枚举可以是where子句中的T,如:

  where T : IComparable 

但是这给出了一个错误:

  where T : IComparable 

然后我想你希望SomeClass具有可比性。 要做到这一点,它必须实现IComparable本身。

以下是两者的示例(使用公共成员保持代码简单):

 public class SomeClass : IComparable> where T : IComparable { public T storedval; public int CompareTo(SomeClass other) { return storedval.CompareTo(other.storedval); } }