Shorthand conditional in C# similar to SQL #39;in#39; keyword(C# 中类似于 SQL in 关键字的简写条件)
问题描述
在 C# 中是否有一种简写方式:
In C# is there a shorthand way to write this:
public static bool IsAllowed(int userID)
{
return (userID == Personnel.JohnDoe || userID == Personnel.JaneDoe ...);
}
喜欢:
public static bool IsAllowed(int userID)
{
return (userID in Personnel.JohnDoe, Personnel.JaneDoe ...);
}
我知道我也可以使用 switch,但是我必须编写大约 50 个这样的函数(将经典的 ASP 站点移植到 ASP.NET),所以我希望它们尽可能短.
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);
}
}
用法:
Personnel userId = Personnel.JohnDoe;
if (userId.In(Personnel.JohnDoe, Personnel.JaneDoe))
{
// Do something
}
我不能为此声称功劳,但我也不记得我在哪里看到的.所以,感谢你,匿名的互联网陌生人.
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 'in' 关键字的简写条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!