C# 中条件简写类似于 SQL 'in' 关键字
-
09-06-2019 - |
题
在 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
}
我不能将此归功于我,但我也不记得我在哪里看到过它。所以,感谢你,匿名的互联网陌生人。
其他提示
像这样的事情怎么样:
public static bool IsAllowed(int userID) {
List<int> IDs = new List<string> { 1,2,3,4,5 };
return IDs.Contains(userID);
}
(当然,您可以根据您的需要更改静态状态、在其他地方初始化 ID 类、使用 IEnumerable<> 等。要点是最接近的等价于 在 SQL 中的运算符是 Collection.Contains() 函数。)
我将允许的 ID 列表封装为 数据 不是 代码. 。这样以后就可以轻松更改其来源。
List<int> allowedIDs = ...;
public bool IsAllowed(int userID)
{
return allowedIDs.Contains(userID);
}
如果使用.NET 3.5,您可以使用 IEnumerable
代替 List
感谢扩展方法。
(这个函数不应该是静态的。看这个帖子: 使用太多静电是坏还是好?.)
权限是否基于用户 ID?如果是这样,您可能会通过基于角色的权限获得更好的解决方案。或者您最终可能不得不频繁地编辑该方法以将其他用户添加到“允许的用户”列表中。
例如,枚举userrole {用户,管理员,洛德梅尔}
class User {
public UserRole Role{get; set;}
public string Name {get; set;}
public int UserId {get; set;}
}
public static bool IsAllowed(User user) {
return user.Role == UserRole.LordEmperor;
}
一个不错的小技巧是反转您通常使用 .Contains() 的方式,例如:-
public static bool IsAllowed(int userID) {
return new int[] { Personnel.JaneDoe, Personnel.JohnDoe }.Contains(userID);
}
您可以在数组中放置任意数量的条目。
如果 Personnel.x 是一个枚举,您会遇到一些转换问题(以及您发布的原始代码),在这种情况下,它会更容易使用:-
public static bool IsAllowed(int userID) {
return Enum.IsDefined(typeof(Personnel), userID);
}
这是我能想到的最接近的:
using System.Linq;
public static bool IsAllowed(int userID)
{
return new Personnel[]
{ Personnel.JohnDoe, Personnel.JaneDoe }.Contains((Personnel)userID);
}
你能为人员编写一个迭代器吗?
public static bool IsAllowed(int userID)
{
return (Personnel.Contains(userID))
}
public bool Contains(int userID) : extends Personnel (i think that is how it is written)
{
foreach (int id in Personnel)
if (id == userid)
return true;
return false;
}
只是另一个语法想法:
return new [] { Personnel.JohnDoe, Personnel.JaneDoe }.Contains(userID);
不隶属于 StackOverflow