【问题标题】:Run correct method based on file name (C#)根据文件名运行正确的方法(C#)
【发布时间】:2019-11-12 23:27:49
【问题描述】:

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

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

基于此,我想要 switch 并运行正确的method。但我很困惑如何正确地做到这一点:

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

【问题讨论】:

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


【解决方案1】:

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

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; 
  }

【讨论】:

  • 方法将在哪里执行??
  • @4est: pair.Value(); 我们得到pair.Value 这是Action 并执行它 - ()
  • 我做了简单的测试方法:private void method1() => Console.WriteLine("test");但它不起作用
  • 我们测试一下:{"FORD", () =&gt; {Console.WriteLine("test");}}, ...
  • 嗨,@ Dmitry,还有一个:我得到了复杂的方法并得到了这个:Argument2:无法从“方法”组转换为“动作”
【解决方案2】:

您可以通过将它们分配给Action来使用c#中的变量等方法:

public void KiaMethod(){
  Console.WriteLine("Kia");
}
public void BmwMethod(){
  Console.WriteLine("BMW");
}

Action method = null;
if(file.Contains("KIA"))
  method = KiaMethod;
else if(file.Contains("BMW"))
  method = BmwMethod;

method();

虽然我真的很喜欢 Keiran 的回答中的模式,因为我真的不明白为什么你需要这种复杂程度

【讨论】:

    猜你喜欢
    • 2011-01-12
    • 1970-01-01
    • 1970-01-01
    • 2011-07-28
    • 2013-07-01
    • 2010-11-15
    • 2021-08-30
    • 2020-09-18
    • 2016-12-16
    相关资源
    最近更新 更多