我有一个类使用 EPPlus 从电子表格中读取文本。它可以工作,并且完全按照我的意愿行事,但我觉得我这样做的方式是不好的做法,但就我的生活而言,我无法找到一种不那么硬编码且使用较少 if 语句的替代方法。 该类包含诸如
之类的常量private static string configUserName;
private static string configPassword;
private static string configUrl;
private static string configDatabase;
//etc
其中大约有 40 个。该类通过电子表格循环读取所有值,检查它是哪个值:
int i = 1;
object isRow = currentWorksheet.Cells[i, 1].Value;
while (isRow != null)
{
if (isRow.ToString().Trim().Equals("change_bank_details_policy"))
{
if (currentWorksheet.Cells[i, 2].Value != null)
{
change_bank_details_policy =c currentWorksheet.Cells[i,2].Value.ToString().Trim();
}
}
else if //etc 40 more if statements
然后因为值是私有(private)的,所以有 40 个方法,例如
public static string GetConfigUserName()
{
return configUserName;
}
一定有更好的方法来做到这一点? 电子表格看起来像
change_bank_details_policy,11459676
change_DD_date_policy,11441975
[40 more rows....]
最佳答案
你能做一个Dictionary吗? (使用键 String
和值 Int
)将字符串和值映射在一起?
一次一行地阅读 Excel 工作表,以构建您的词典。
然后使用字典设置适当的变量。
然后你的字典看起来像:
KEY VALUE
============================|========
change_bank_details_policy |11459676
change_DD_date_policy |11441975
在构建字典之后,您可以简单地执行以下操作:
change_bank_details_policy = my_dictionary["change_bank_details_policy"];
我认为大纲应该是这样的:
Dictionary<String, UInt32> myDict = new Dictionary<String, UInt32>();
object isRow = currentWorksheet.Cells[i, 1].Value;
while (isRow != null)
{
myDict.Add(isRow.ToString().Trim(), currentWorksheet.Cells[i,2].Value);
// Go get the next Row.... details are up to you.
}
change_bank_details_policy = myDict["change_bank_details_policy"]; // Look up this key in the dictionary to get this integer....
change_DD_date_policy = myDict["change_DD_date_policy"];
// [... repeat 40 more times ... but no If statements ]
关于c# - 太多的 If 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22640339/