通用功能的拳击错误

时间:2013-08-08 18:02:02

标签: c# generics boxing

如果我注释掉我的静态类,那么编译就好了。但是我想让静态类工作,所以我可以使用main中第一个注释掉的行。我的错误是

  

错误CS0314:类型'T'不能用作泛型类型或方法'DateTest.Range'中的类型参数'T'。从'T'到'System.IComparable'没有装箱转换或类型参数转换。

我的来源是

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DateTest
{
    class Program
    {
        static void Main(string[] args)
        {
            //Range.Create(new DateTime(2013, 1, 1), new DateTime(2015, 1, 1), s => s.AddYears(1));
            new Range<DateTime>(new DateTime(2013, 1, 1), new DateTime(2015, 1, 1), s => s.AddYears(1));
        }
    }
    static class Range { public static Range<T> Create<T>(T s, T e, Func<T,T> inc) { return new Range<T>(s, e, inc); } }
    class Range<T> : IEnumerator<T> where T : IComparable 
    {
        T start, pos, end;
        Func<T,T> inc;
        public Range(T s, T e, Func<T,T> inc) { pos=start= s; end = e; this.inc = inc; }

        public T Current
        {
            get { return pos; }
        }

        public void Dispose()
        {
            throw new NotImplementedException();
        }

        object System.Collections.IEnumerator.Current
        {
            get { return pos; }
        }

        public bool MoveNext()
        {
            pos = inc(pos);
            return pos.CompareTo(end) != 0;
        }

        public void Reset()
        {
            pos = start;
        }
    }
}

1 个答案:

答案 0 :(得分:3)

您的静态Create方法需要具有Range<T>类适用于泛型参数的所有约束:

static class Range
{
    public static Range<T> Create<T>(T s, T e, Func<T, T> inc)
        where T : IComparable  //this line was added
    {
        return new Range<T>(s, e, inc);
    }
}

就是这样。

由于Range类要求T具有可比性,Create方法需要确保其自己的T也具有可比性。

在旁注中,您可以考虑使用IComparable<T>作为两者的约束,而不是IComparable,以确保比较的静态类型。

公约还会声明Range实现IEnumerable<T>而不是IEnumerator<T>,以便同一范围可以同时由多个来源迭代,并且它还允许您使用foreach循环以及构建在IEnumerable<T>接口上的许多其他库方法(即所有LINQ)。