将变量与多个值进行比较 [英] Comparing a variable to multiple values

查看:87
本文介绍了将变量与多个值进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的代码中经常需要将变量与多个值进行比较:

Quite often in my code I need to compare a variable to several values :

if ( type == BillType.Bill || type == BillType.Payment || type == BillType.Receipt )
{
  // Do stuff
}

我一直认为自己可以做到:

I keep on thinking I can do :

if ( type in ( BillType.Bill, BillType.Payment, BillType.Receipt ) )
{
   // Do stuff
}

但是当然那是SQL允许的。

But of course thats SQL that allows this.

C#中有更整齐的方法吗?

Is there a tidier way in C#?

推荐答案

您可以使用。包含以下内容:

You could do with with .Contains like this:

if(new[]{BillType.Receipt,BillType.Bill,BillType.Payment}.Contains(type)){}

或者,创建自己的扩展方法,使其使用更易读的语法

Or, create your own extension method that does it with a more readable syntax

public static class MyExtensions
{
    public static bool IsIn<T>(this T @this, params T[] possibles)
    {
        return possibles.Contains(@this);
    }
}

然后通过以下方式调用它:

Then call it by:

if(type.IsIn(BillType.Receipt,BillType.Bill,BillType.Payment)){}

这篇关于将变量与多个值进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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