Shorthand conditional in C# similar to SQL 'in' keyword

后端 未结 8 2228
北恋
北恋 2021-01-04 12:44

In C# is there a shorthand way to write this:

public static bool IsAllowed(int userID)
{
    return (userID == Personnel.JohnDoe || userID == Personnel.JaneD         


        
8条回答
  •  滥情空心
    2021-01-04 13:16

    I would encapsulate the list of allowed IDs as data not code. Then it's source can be changed easily later on.

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

    If using .NET 3.5, you can use IEnumerable instead of List thanks to extension methods.

    (This function shouldn't be static. See this posting: using too much static bad or good ?.)

提交回复
热议问题