gpt4 book ai didi

c# - 在 C# 中处理 switch case 的更好方法

转载 作者:行者123 更新时间:2023-11-30 13:29:52 24 4
gpt4 key购买 nike

如果我的问题看起来真的很愚蠢,我会提前道歉,但出于某种原因,我无法查看更优雅的问题解决方案。所以我有一个方法利用类似于下面代码块的 switch-case block :

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)
  • 不允许声明此方法

非常感谢任何建议..

最佳答案

您可以将 enum ItemsString_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);
}

您可能需要检查 item 参数是否具有有效映射,如果不存在则使用默认字符串。

关于c# - 在 C# 中处理 switch case 的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47601451/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com