检查字符串变量值是否是 C# 中指定值集之一的智能方法是什么?



>我正在编写一个简单的 C#.NET 应用程序,其中我有一个 if 条件,我正在检查字符串变量值是字符串还是另一个字符串或另一个字符串或另一个字符串等。

像这样:

if(protocollo == "2019/0002391" || protocollo == "2019/0002390" || protocollo == "2019/0001990" || ........)

这个解决方案有效,但它不是那么优雅。实现相同行为的更智能方法是什么?

我同意@JeroenMostert的观点,即这实际上取决于应用程序其余部分的上下文。也就是说,使用字符串数组并检查您的字符串是否在其中是一个很好的直接解决方案。有一些解决方案可以更好地扩展,看看HashSet。

string[] s = new string[] { "2019/0002391", "2019/0002390", "2019/0001990", ... };
if (s.Contains(protocollo)) {
    // fill in here
}

你从来没有说过,所以我假设你正在检查的字符串是硬编码的,而不是经常更改的东西。为此,您可以在静态类中创建string[]HashSet<string>,以便它只初始化一次,然后公开一个方法,用于根据有效字符串检查第二个字符串。

void Main()
{
    Console.WriteLine(Protocols.ValidProtocol("2019/0002391")); //True
    Console.WriteLine(Protocols.ValidProtocol("2018/0000000")); //False
}
// Define other methods and classes here
public static class Protocols
{
    public static bool ValidProtocol(string protocol)
    {
        return _validProtocols.Contains(protocol);
    }
    private static readonly HashSet<string> _validProtocols = new HashSet<string>
    {
        "2019/0002391",
        "2019/0002390",
        "2019/0001990"
        //etc, etc...
    };
}

如果您需要经常检查更改string列表,则这样的解决方案可能并不理想。如果需要经常修改列表,则可能需要从外部源(如文件或数据库(中提取列表。

我在静态扩展方法中有一些类似于您的示例的代码。我不想每次调用该方法时都必须实例化数组,但我想提高代码的可读性。

我使用 C# 8 中添加的开关表达式改进了代码。下面是使用开关表达式实现时的示例可能的外观。如果条件为真,则根据代码的作用,您也许可以对此进行改进,但这是基础知识。

var isProtocolloMatch = protocollo switch
{
    "2019/0002391" => true,
    "2019/0002390" => true,
    "2019/0001990" => true,
    _ => false
};
if (isProtocolloMatch)
{
    // do stuff
}

最新更新