开发者

Why C# compiler can't understand generic arguments used in separate classes?

Here is my code:

public class Range<TNum> where TNum : IComparable
{
    public TNum From { get; set; }
    public TNum To { get; set; }
}

public class MarkableRange<TNum> where TNum : IComparable
{
    private readonly List<Range<TNum>> _markedRanges = new List<Range<TNum>>();

    public void MarkOne(TNum number)
    {
        _markedRanges.Where(r => number >= r.From && number <= r.To);
    }
}

compiler says that it cannot apply operator >= on operands in number >= r.From and number <= r.To

I could get away with List<Tuple<TNum, TNum>> but i wanted something more meaningful. So is i开发者_开发技巧t me who did something wrong or c# compiler not that smart to understand my intention?


TNum is constrained to implement IComparable, which doesn't have the operators you're using (<= and >=). You should use the CompareTo method instead:

public void MarkOne(TNum number) {
  _markedRanges.Where(r => number.CompareTo(r.From) >= 0 && number.CompareTo(r.To) <= 0);
}

To use the operators, take a look here.

Also, prefer the generic IComparable<T>.


You can overload operators in C#, so you could define the >= and <= operators on your Range class that delegates to the IComparable implementation. Should work then.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜