Tir*_*ing 3 c# enums coding-style
如果我的问题看起来很愚蠢,我会提前道歉,但由于某种原因,我无法通过更优雅的解决方案来解决问题.所以我有一个利用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);
Run Code Online (Sandbox Code Playgroud)
从上面的示例可以看出,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)
Run Code Online (Sandbox Code Playgroud)
任何建议都非常感谢..
你可以存储enum Items到String_X映射在字典中,而不是依靠一个开关.
private IDictionary<Items, string> _itemStringMap = new Dicitionary<Items, string>()
{
{ Items.item_1, String_1 },
//Other items here
};
public void DoSomething(Items item)
{
var s = _itemStringMap[item];
MethodNumberOne();
MethodNumberTwo();
MethodNumberThree();
Console.WriteLine($"{0} is displayed on the page", s);
}
Run Code Online (Sandbox Code Playgroud)
您可能想要检查item参数是否具有有效映射,如果不使用默认字符串.