开发者

How can I get all values between two variables of type T?

If I have two variables of type T, would it be possible to get all of the values in between the two variables, assuming that both T types are the same?

I am working in .net 2.0 and have built a Range class based on this code: Intersection of Date Ranges

If I know that the type is DateTime, it is easy to loop through the dates easily to g开发者_运维百科et to from the Start value to the End value. Like so:

List<DateTime> values = new List<DateTime>();

for (DateTime d = myRange.Start; d <= myRange.End; d = d.AddDays(1))
{
    values.Add(d);
}

But, to make this more generic, is there a way to do this any type T?

Am I asking for something impossible?


You can do something like this with an IComparable<T>.

public static List<T> GetRange(T start, T end, Func<T,T> increment)
{
    List<T> result = new List<T>();
    for(T t = start; t.CompareTo(end) < 0; t = increment(t))
    {
        result.Add(t);
    }
    return result;
}

List<DateTime> values = GetRange<DateTime>(myRange.Start, myRange.End, d => d.AddDays(1));

The increment function needs to be provided manually for a couple reasons: First, some IComparables don't have a natural increment function: String, for instance. Second, even if there is an increment function, there's no way to find it. Even with your example of DateTimes, there's no way to be sure you wanted AddDays(1), not AddSeconds(1).


I think this would be impossible to use on any type T. Not all forms would have a sortable value with distinct steps between them. An integer from 0-10 is simple. The same is for your example above.

But how do you get from "boat" to "truck"? I don't think it can be applied to just any form that easily.


Did you try it?

You can do that but it will only work with types that can be compared in this way.


What you are asking for cannot be done with generics as implemented in .net. Your best bet is to define an interface that specifies the operations you need and apply a constraint to T.

You could do it with C++ templates for integral values. It would also be trivial in a language that used duck typing.


Given that T could be a type that only has one value, I cannot see how this could be solved generically. It may be possible if T supports and interface that allows it's range to be determined.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜