如果值在 range(x,y) 函数 c# [英] If value in range(x,y) function c#

查看:129
本文介绍了如果值在 range(x,y) 函数 c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

c# 是否有一个函数可以为表达式返回一个布尔值:if(value.inRange(-1.0,1.0)){}?

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

推荐答案

说明

我建议您使用扩展方法.

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.

您可以以通用方式创建此扩展方法(感谢 digEmAll 和 CodeInChaos,他们建议这样做).然后你可以在每个实现 IComparable 的对象上使用它.

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.

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;
    }
}

然后你这样做

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

完美主义者的更新

在与@CodeInChaos 进行广泛讨论后,他说

Update for perfectionists

After an extensive discussion with @CodeInChaos who said

我可能会按照之前的评论中的建议使用 IsInOpenInterval.但我不确定没有数学背景的程序员是否会理解该术语.

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.

您也可以将函数命名为 IsInOpenInterval.

You can name the function IsInOpenInterval too.

这篇关于如果值在 range(x,y) 函数 c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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