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' 关键字的简写条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C# 中类似于 SQL 'in' 关键字的简写条件


基础教程推荐
- SSE 浮点算术是否可重现? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- c# Math.Sqrt 实现 2022-01-01