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

标签 c# lambda conditional if-statement

在 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<T>(this T testValue, params T[] values)
    {
        return values.Contains(testValue);
    }
}

用法:

Personnel userId = Personnel.JohnDoe;

if (userId.In(Personnel.JohnDoe, Personnel.JaneDoe))
{
    // Do something
}

这不能归功于我,但我也不记得我在哪里看到的。所以,归功于你,匿名的互联网陌生人。

关于c# - C# 中的简写条件类似于 SQL 'in' 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32937/

相关文章:

c# - 查看详细信息窗口不会展开集合属性

c# - 如何确定EventWaitHandle.WaitOne是否在辅助线程中被调用

lambda - 为什么`id id`在OCaml中不是值?

c++ - C++ 14中的通用Lambda

if-statement - Dart 空/假/空检查 : How to write this shorter?

c# - 什么是 Xamarin.Forms 等效于 layoutSubviews?

c# - 将文件上传存储到 MemoryStream (C#) 的最佳做法是什么?

function - 什么是 PowerShell ScriptBlock

.net - 根据项目配置有条件地包含文件

java - Java 中的#ifdef#ifndef