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

☆樱花仙子☆ 提交于 2019-12-23 10:17:33

问题


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


回答1:


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

  • MSDN - Extension Methods (C# Programming Guide)
  • MSDN - IComparable Interface



回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/8776624/if-value-in-rangex-y-function-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!