c# - 根据文件名运行正确的方法 (C#)

标签 c# if-statement switch-statement boolean boolean-logic

我正在检查文件的名称,如果正确则返回TRUE:

bool name_FORD = file.Contains("FORD"); 
bool name_KIA  = file.Contains("KIA");  
bool name_BMW  = file.Contains("BMW");

基于此,我想要切换 并运行正确的方法。但我不知道如何正确地做到这一点:

switch (true)
{
 case 1 name_FORD: 
              method1();
              break();
 case 2 name_KIA:
              method2();
              break();
 case 3 name_BMW:
              method3();
              break();
}

最佳答案

我建议组织所有字符串和相应的方法作为字典:

Dictionary<string, Action> myCars = new Dictionary<string, Action>() {
  {"FORD", method1}, // e.g. {"FORD", () => {Console.WriteLine("It's Ford!");}},
  { "KIA", method2},
  { "BMW", method3}, 
  //TODO: Put all the cars here
};

然后我们可以放一个简单的循环:

foreach (var pair in myCars)
  if (file.Contains(pair.Key)) { // if file contains pair.Key
    pair.Value();                // we execute corresponding method pair.Value

    break; 
  }

编辑如果我们可以有复杂的方法(例如方法可能需要filekey 参数)我们可以更改签名:

// Each action can have 2 parameters: key (e.g. "FORD") and file
Dictionary<string, Action<string, string>> myCars = 
  new Dictionary<string, Action<string, string>>() {
     {"FORD", (key, file) => {Console.Write($"{key} : {string.Concat(file.Take(100))}")}}, 
     { "KIA", (key, file) => {Console.Write($"It's {key}!")}},
     { "BMW", (key, file) => {/* Do nothing */}}, 
  //TODO: Put all the cars here
};

在循环中执行时,我们应该提供这些参数:

foreach (var pair in myCars)
  if (file.Contains(pair.Key)) { // if file contains pair.Key
    pair.Value(pair.Key, file); // we execute corresponding method pair.Value

    break; 
  }

关于c# - 根据文件名运行正确的方法 (C#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56850365/

相关文章:

javascript - Switch 语句实现未提供预期行为

java - 如何从一串数字中获取数值?

c# - 如何访问azure webrole中的signalr hub

linux - 带有 grep 的 Bash 函数,使用 if 和 then 语句

c# - Azure ServiceBus 在 Client.Receive() 上返回 null

使用 Integer.parseInt 时出现 Java NumberFormatException

c++ - C/C++ : switch for non-integers

java - 用户选择的选项不会触发if语句

c# - C# 中条件编译的替代方案

c# - 什么是实现类似 Dictionary<string, string, Dictionary<string, string>> 的好方法?