不必实现比操作比一般的少和更大 [英] Having to implement a generic less than and greater than operation

查看:187
本文介绍了不必实现比操作比一般的少和更大的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我绝对不能硬编码的数据类型。我需要严格的数据类型。我必须使用TValue A< = TValue湾再次,是绝对没有办法做到像(双)一个。这是一个重要的库实现的一部分。这是具体介绍一下通用值的唯一的事情是,他们是静态类型。 IComparable的其他接口似乎不工作。

I absolutely CANNOT hard code a data type. I need strict data typing. I have to use TValue a <= TValue b. Again, there is ABSOLUTELY NO way to do something like (double) a. This is part of an essential library implementation. The only thing that is specific about the generic values is that they are of static types. IComparable and other interfaces don't seem to work.

推荐答案

为什么你不IComparable的工作?

Why doesn't IComparable work for you?

您可能没有获得使用的语法糖<和>符号,但你可以检查,看看是否的CompareTo的结果小于或大于0时,它给你同样的信息。

You may not get the syntactic sugar of using the "<" and ">" symbols, but you can check to see if the result of CompareTo is less than or greater than 0, which gives you the same information.

您甚至可以写一个很好的扩展方法,使其更易于使用。

You could even write a nice extension method to make it easier to work with.

static void Main(string[] args)
{
    Console.WriteLine(1.IsGreaterThan(2));
    Console.WriteLine(1.IsLessThan(2));
}

public static bool IsGreaterThan<T>(this T value, T other) where T : IComparable
{
    return value.CompareTo(other) > 0;
}

public static bool IsLessThan<T>(this T value, T other) where T : IComparable
{
    return value.CompareTo(other) < 0;
}

这篇关于不必实现比操作比一般的少和更大的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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