If value in range(x,y) function c#

2019-06-22 05:41发布

Does c# have a function that returns a boolean for expression : if(value.inRange(-1.0,1.0)){}?

标签: c# range
3条回答
冷血范
2楼-- · 2019-06-22 06:23

Description

I suggest you use a extension method.

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.

You can create this extension method in a generic way (thx to digEmAll and CodeInChaos, who suggest that). Then you can use that on every object that implements IComparable.

Solution

public static class IComparableExtension
{
    public static bool InRange<T>(this T value, T from, T to) where T : IComparable<T>
    {
        return value.CompareTo(from) >= 1 && value.CompareTo(to) <= -1;
    }
}

then you do this

double t = 0.5;
bool isInRange = t.InRange(-1.0, 1.0);

Update for perfectionists

After an extensive discussion with @CodeInChaos who said

I'd probably go with IsInOpenInterval as suggested in an earlier comment. But I'm not sure if programmers without a maths background will understand that terminology.

You can name the function IsInOpenInterval too.

More Information

查看更多
疯言疯语
3楼-- · 2019-06-22 06:29

Use Math.Abs(value) <= 1.0 for example

查看更多
ゆ 、 Hurt°
4楼-- · 2019-06-22 06:31

Not very clear, but may be inverse:

Enumerable. Range(-1, 2).Any(x=>x==value).

By the way didn't compile this, writing from mobile.

edit

here I'm using Enumerable.Range

edit1

if we are talking about floating point numbers, it's enough to create an extension method which generates the sequence of numbers by specifying start number and offset step and after execute Any<T> on resulting collection, like in aswer provided.

查看更多
登录 后发表回答