速记有条件在C#中类似“在'SQL关键字 [英] Shorthand conditional in C# similar to SQL 'in' keyword

查看:176
本文介绍了速记有条件在C#中类似“在'SQL关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中有没有写这个简写方式:

In C# is there a shorthand way to write this:

public static bool IsAllowed(int userID)
{
    return (userID == Personnel.JohnDoe || userID == Personnel.JaneDoe ...);
}



我爱:

Like:

public static bool IsAllowed(int userID)
{
    return (userID in Personnel.JohnDoe, Personnel.JaneDoe ...);
}



我知道我还可以使用开关,但也有可能是50左右功能这样我不得不写(到ASP.NET移植传统的ASP网站),所以我想,让他们尽可能短。

I know I could also use switch, but there are probably 50 or so functions like this I have to write (porting a classic ASP site over to ASP.NET) so I'd like to keep them as short as possible.

推荐答案

这个怎么样?

public static class Extensions
{
    public static bool In<T>(this T testValue, params T[] values)
    {
    	return values.Contains(testValue);
    }
}



用法:

Usage:

Personnel userId = Personnel.JohnDoe;

if (userId.In(Personnel.JohnDoe, Personnel.JaneDoe))
{
    // Do something
}

我不能居功,但我也想不起来在那里我看到了它。所以,信用给你,匿名Internet陌生人。

I can't claim credit for this, but I also can't remember where I saw it. So, credit to you, anonymous Internet stranger.

这篇关于速记有条件在C#中类似“在'SQL关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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