【发布时间】:2017-11-22 22:01:05
【问题描述】:
如果我的问题看起来很愚蠢,我会提前道歉,但由于某种原因,我无法通过更优雅的解决方案来解决问题。所以我有一个使用类似于以下代码块的 switch-case 块的方法:
public enum Items
{
item_1, item_2, item_3, .... item_N
};
private string String_1 {get; set;}
private string String_2 {get; set;}
private string String_3 {get; set;}
// ...
private string String_N {get; set;}
public void DoSomething(Items item){
switch(item){
case item_1:
MethodNumberOne();
MethodNumberTwo();
MethodNumberThree();
Console.WriteLine($"{0} is displayed on the page", String_1);
break;
case item_2:
MethodNumberOne();
MethodNumberTwo();
MethodNumberThree();
Console.WriteLine($"{0} is displayed on the page", String_2);
break;
case item_3:
MethodNumberOne();
MethodNumberTwo();
MethodNumberThree();
Console.WriteLine($"{0} is displayed on the page", String_3);
break;
// ...
case item_N:
MethodNumberOne();
MethodNumberTwo();
MethodNumberThree();
Console.WriteLine($"{0} is displayed on the page", String_N);
从上面的例子中可以看出switch语句调用的方法是一样的,唯一的区别就是最后一次Console调用。
我的问题:有没有更优雅的方法来处理这种情况,因为我不太喜欢重复代码。到目前为止,我尝试执行 Items 枚举以分离类并将其作为参数传递,但这种方法不起作用,因为静态类不能作为 C# 中的参数传递
public static class Items {
public string String_1 {get; set;}
public string String_2 {get; set;}
public string String_3 {get; set;}
// ...
private string String_N {get; set;}
}
// ....
public void DoSomething(Items item)
- 不允许声明此方法
任何建议都非常感谢..
【问题讨论】:
-
你可以使用一个数组来保存你的 String_1、String_2 等项目(例如,称为 stringsArray[])然后你可以像这样访问它们 stringsArray[item_1] 而不是 Console.WriteLine($" {0} 显示在页面上", String_2);你会有 Console.WriteLine($"{0} is shown on the page", stringsArray[item_2]);
-
或者,考虑
Dictionary<Items, string> -
在进入 switch 块之前,调用这三个方法。在 switch 块中,按照您现在的方式调用控制台。这很简单。
标签: c# coding-style enums