C#中的简写条件类似于”’关键字中的SQL’

在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(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 IDs = new List { 1,2,3,4,5 }; return IDs.Contains(userID); } 

(您当然可以根据您的需要更改静态状态,在其他地方初始化ID类,使用IEnumerable <>等。重点是SQL中与in运算符最接近的等价物是Collection。包含()函数。)

我会将允许的ID列表封装为数据而不是代码 。 然后它的源可以在以后轻松更改。

 List allowedIDs = ...; public bool IsAllowed(int userID) { return allowedIDs.Contains(userID); } 

如果使用.NET 3.5,由于扩展方法,您可以使用IEnumerable而不是List

(这个function不应该是静态的。看看这个贴子: 使用太多静态坏或好? )

权限是否基于用户ID? 如果是这样,您可以通过转到基于角色的权限来获得更好的解决方案。 或者,您可能最终必须经常编辑该方法,才能将其他用户添加到“允许的用户”列表中。

例如,枚举UserRole {User,Administrator,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); } 

你能为Personnel写一个迭代器吗?

 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);