根据文件名(C#)运行正确的方法
我正在检查根据文件名(C#)运行正确的方法,c#,if-statement,switch-statement,boolean,boolean-logic,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();
文件的名称
,如果正确,则返回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
};
编辑:如果我们可以使用复杂的方法(例如,方法可能需要文件
和键
参数),我们可以更改签名:
// 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
};
通过将变量分配给动作,可以使用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答案中的模式,因为我不明白为什么需要这种复杂程度,如果文件包含所有这三个呢?使用嵌套的if-else…你不需要一个
开关,只需要几个if
-stamenets:if(name_FORD){method1;}
。可能的重复我担心,除非您使用的是c#7.0,否则在简单的开关/案例中是不可能的。方法将在何处执行???@4est:pair.Value()
我们得到pair.Value,也就是Action
并执行它-()
我做了一个简单的测试方法:private void method1()=>Console.WriteLine(“测试”);但这不符合林格勒的测试:{“FORD”,()=>{Console.WriteLine(“test”);},
hi,@Dmitry,还有一个:我得到了复杂的方法,得到了这个:Argument2:无法从“method”组转换为“Action”
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;
}
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();