C#拳击枚举错误与泛型 [英] C# boxing enum error with generics

查看:119
本文介绍了C#拳击枚举错误与泛型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我有以下错误:
类型'TestApp.TestVal'不能用于通用类型或方法中的类型参数'T' 'TestApp.SomeClass< T>'。没有从'TestApp.TestVal''System.IComparable< TestApp.TestVal>'的拳击转换。 / em>



以下代码发生此错误:

  public枚举TestVal 
{
首先,
第二,
第三个
}

public class SomeClass< T>
其中T:IComparable< T>
{
public T存储
{
get
{
return storedval;
}
set
{
storedval = value;
}
}
private T storedval;
}

类程序
{
static void Main(string [] args)
{
//错误在下一行
SomeClass< TestVal> t = new SomeClass< TestVal>();
}
}

由于枚举是一个 int 默认情况下,int实现 IComparable< int> 接口似乎不应该有错误....

解决方案

首先,我不知道使用 IComparable< T> 有一个枚举... IEquatable< T> ,但是比较?



作为一个更安全的选择;而不是使用通用约束来命名 IComparable< T> ,可以在类中使用 Comparer&T; .Default 。这有利于支持 IComparable< T> IComparable - 这意味着您传播的限制较少。 / p>

例如:

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

可以使用枚举:

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


I don't understand what is going on here...

I've got the following error: The type 'TestApp.TestVal' cannot be used as type parameter 'T' in the generic type or method 'TestApp.SomeClass<T>'. There is no boxing conversion from 'TestApp.TestVal' to 'System.IComparable<TestApp.TestVal>'.

This error happens for the following code:

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>(); 
    }
}

Since the enum is an int by default and int's implement the IComparable<int> interface it seems like there shouldn't be an error....

解决方案

Firstly, I'm not sure whether it is sensible to use IComparable<T> with an enum... IEquatable<T>, sure - but comparison?

As a safer alternative; rather than mandate the IComparable<T> with the generic constraint, perhaps use Comparer<T>.Default inside the class. This has the advantage of supporting IComparable<T> and IComparable - and it means you have less constraints to propagate.

For example:

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

This works fine with the enum:

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

这篇关于C#拳击枚举错误与泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆