在 C# 中有一种简写的方式来写这个:
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),所以我希望它们尽可能短。
最佳答案
这个怎么样?
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
}
这不能归功于我,但我也不记得我在哪里看到的。所以,归功于你,匿名的互联网陌生人。
关于c# - C# 中的简写条件类似于 SQL 'in' 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32937/