C#box枚举错误与泛型

5 c# generics enums icomparablet

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

我有以下错误: 该类型'TestApp.TestVal'不能用作'T'泛型类型或方法中的类型参数'TestApp.SomeClass<T>'.没有来自装箱转换'TestApp.TestVal''System.IComparable<TestApp.TestVal>'.

以下代码发生此错误:

public enum TestVal
{
    First,
    Second,
    Third
}

public class SomeClass<T>
    where T : IComparable<T>
{
    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<TestVal> t = new SomeClass<TestVal>(); 
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*ell 8

首先,我不确定使用IComparable<T>枚举是否明智...... IEquatable<T>,当然 - 但比较一下?

作为一种更安全的选择; 而不是强制IComparable<T>使用泛型约束,也许Comparer<T>.Default在类中使用.这具有支持IComparable<T>IComparable- 的优势,这意味着您传播的约束较少.

例如:

public class SomeClass<T> { // note no constraint
    public int ExampleCompareTo(T other) {
        return Comparer<T>.Default.Compare(Stored, other);
    }
    ... [snip]
}
Run Code Online (Sandbox Code Playgroud)

这适用于枚举:

SomeClass<TestVal> t = new SomeClass<TestVal>();
t.Stored = TestVal.First;
int i = t.ExampleCompareTo(TestVal.Second); // -1
Run Code Online (Sandbox Code Playgroud)


Mar*_*ann 5

枚举不是从System.Int32s派生的 - 它们派生自System.Enum,但它没有实现IComparable<int>(IComparable尽管它实现了).

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