C#中类似于SQL'in'关键字的速记条件
时间:2020-03-05 18:44:33 来源:igfitidea点击:
在Cis中,有一种写这种方式的简便方法:
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),所以我想使它们尽可能短。
解决方案
回答
我会将允许的ID列表封装为数据而不是代码。然后,可以在以后轻松更改其来源。
List<int> allowedIDs = ...; public bool IsAllowed(int userID) { return allowedIDs.Contains(userID); }
如果使用.NET 3.5,则由于扩展方法的缘故,我们可以使用IEnumerable
而不是List
。
(此功能不应是静态的。请参见此文章:使用太多的静态不良或者不良?。)
回答
这样的事情怎么样:
public static bool IsAllowed(int userID) { List<int> IDs = new List<string> { 1,2,3,4,5 }; return IDs.Contains(userID); }
(当然,我们可以根据需要更改静态状态,在其他地方初始化ID类,使用IEnumerable <>等)。要点是,SQL中与in运算符最接近的等效项是Collection。 Contains()函数。)
回答
权限是否基于用户标识?如果是这样,我们可以通过转到基于角色的权限来获得更好的解决方案。或者,我们可能最终不得不非常频繁地编辑该方法,以将其他用户添加到"允许的用户"列表中。
例如,
枚举UserRole {
用户,管理员,LordEmperor
}
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); }
回答
只是另一个语法概念:
return new [] { Personnel.JohnDoe, Personnel.JaneDoe }.Contains(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; }
回答
这个怎么样?
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 }
我无法为此赞誉,但我也不记得在哪里看到它。因此,请相信我们,匿名的Internet陌生人。