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

Mar*_*all 11 c# lambda conditional if-statement

在C#中有一种写简单的简写方法:

public static bool IsAllowed(int userID)
{
    return (userID == Personnel.JohnDoe || userID == Personnel.JaneDoe ...);
}
Run Code Online (Sandbox Code Playgroud)

喜欢:

public static bool IsAllowed(int userID)
{
    return (userID in Personnel.JohnDoe, Personnel.JaneDoe ...);
}
Run Code Online (Sandbox Code Playgroud)

我知道我也可以使用switch,但是我可能要编写50个左右这样的函数(将一个经典的ASP站点移植到ASP.NET),所以我想让它们尽可能短.

Jon*_*ara 13

这个怎么样?

public static class Extensions
{
    public static bool In<T>(this T testValue, params T[] values)
    {
        return values.Contains(testValue);
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

Personnel userId = Personnel.JohnDoe;

if (userId.In(Personnel.JohnDoe, Personnel.JaneDoe))
{
    // Do something
}
Run Code Online (Sandbox Code Playgroud)

我不能为此声称自己,但我也记不住在哪里看到它.所以,归功于你,匿名的互联网陌生人.