通用的InBetween函数

Lui*_*cio 4 c# generics

我厌倦了写作,x > min && x < max所以我想写一个简单的函数,但我不确定我是否做得对...实际上我不是因为我得到一个错误:

    bool inBetween<T>(T x, T min, T max) where T:IComparable
    {
        return (x > min && x < max);
    }
Run Code Online (Sandbox Code Playgroud)

错误:

Operator '>' cannot be applied to operands of type 'T' and 'T'
Operator '<' cannot be applied to operands of type 'T' and 'T'  
Run Code Online (Sandbox Code Playgroud)

我可能where对函数声明中的部分有一个不好的理解

注意:对于那些打算告诉我我将编写比以前更多的代码的人...想想可读性=)任何帮助将不胜感激

编辑

删除因为它被解决了=)

另一个编辑

所以在经过一番头痛之后,我在@Jay极端可读性的想法之后出现了这个(嗯)的事情:

public static class test
{
    public static comparision Between<T>(this T a,T b) where T : IComparable
    {
        var ttt = new comparision();
        ttt.init(a);
        ttt.result = a.CompareTo(b) > 0;
        return ttt;
    }

    public static bool And<T>(this comparision state, T c) where T : IComparable
    {
        return state.a.CompareTo(c) < 0 && state.result;
    }

    public class comparision
    {
        public IComparable a;
        public bool result;          
        public void init<T>(T ia) where T : IComparable
        {
            a = ia;
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

现在你可以比较极端可读性的东西=)

你觉得怎么样......我不是表演大师,所以欢迎任何调整

Yur*_*ich 5

IComparable意味着该对象实现了CompareTo方法.使用

public static bool InBetween<T>(this T x, T min, T max) where T:IComparable<T>
{
    return x.CompareTo(min) > 0 && x.CompareTo(max) < 0;
}
Run Code Online (Sandbox Code Playgroud)