2008-08-28 44 views
9

在C#中有沒有寫這個的簡便方法:在C#中類似「在」關鍵字SQL速記條件

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

我知道我還可以使用開關,但大概有50個左右的函數需要我編寫(將一個經典的ASP站點移植到ASP.NET上),所以我想盡可能縮短它們。

回答

13

這個怎麼樣?

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 
} 

我不能居功,但我怎麼也想不起在哪裏見過。所以,相信你,匿名互聯網陌生人。

+0

這太美了! – amrtn 2009-05-20 09:12:29

2

我會封裝允許的ID列表爲數據不是代碼。然後它的源碼可以在以後輕鬆更改。

List<int> allowedIDs = ...; 

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

如果使用.NET 3.5,您可以使用IEnumerable代替List感謝擴展方法。

(此功能不應該是靜態看到這個帖子:。using too much static bad or good ?

4

怎麼是這樣的:

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()函數。)

1

權限是否基於用戶標識?如果是這樣,您可以通過轉到基於角色的權限獲得更好的解決方案。或者您可能最終不得不經常編輯該方法,以將其他用戶添加到「允許的用戶」列表中。

例如, 枚舉的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; 
} 
+0

我很樂意這樣做,但遺憾的是我們對遺留代碼太深入了。 – Marshall 2008-08-28 18:19:13

0

一個不錯的小竅門是那種顛倒您通常使用。載有()的方式,如: -

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

下面是我能想到的最接近的:

using System.Linq; 
public static bool IsAllowed(int userID) 
{ 
    return new Personnel[] 
     { Personnel.JohnDoe, Personnel.JaneDoe }.Contains((Personnel)userID); 
} 
0

又一個語法的想法:

return new [] { Personnel.JohnDoe, Personnel.JaneDoe }.Contains(userID); 
0

你能寫ITER人事代理人。

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