If语句太多了?

时间:2014-03-25 16:15:12

标签: c# epplus

我有一个类,使用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

然后因为这些值是私有的,所以有40种方法,例如

public static string GetConfigUserName()
    {
        return configUserName;
    }

必须有更好的方法吗? 电子表格看起来像

change_bank_details_policy,11459676
change_DD_date_policy,11441975
[40 more rows....]

4 个答案:

答案 0 :(得分:4)

您可以制作一个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 ]

答案 1 :(得分:2)

问题的根源在于你有~40个变量,这是一个明确的code smell。您应该考虑使用Dictionary来存储它们 - 而不是广泛使用变量。

Dictionary正在映射&#39;键&#39;价值&#39;。在您的情况下,它将从字符串映射到字符串(如果您确实需要一个字符串)。

答案 2 :(得分:0)

已经提到了切换语句,但C#中的一个非常好的功能是你可以将变量的直接访问权限设置为只读,所以为了回答第二个问题,你的变量可能有以下语法:

private static string configUserName
{
    public get;
    private set;
}

哪个允许你的类成员直接访问变量,但是如果用户试图直接写入它会导致编译器错误(但如果他们试图读取它则不会),例如:

instance.configUserName = "Bob";

将在类成员代码中工作,但不会在用户代码中编译,而:

String bob = instance.configUserName;

将在两个地方编译。

答案 3 :(得分:0)

以下代码不会覆盖未读取的值。如果源文件中不存在行,则先前的值不会丢失。我认为它对源文件内容有点防范。

var dict = new Dictionary<string, Action<long>>();
dict.Add("change_bank_details_policy", v => change_bank_details_policy = v);
// 40 of these, no choice

int i = 1;
object isRow = currentWorksheet.Cells[i, 1].Value;
while (isRow != null)
{
    string rowTitle = isRow.ToString().Trim();
    if (dict.ContainsKey(rowTitle))
    {
        // Or parse it or whatever you have to do to handle the cell value type
        long rowValue = currentWorksheet.Cells[i,2].Value; 
        dict[rowtitle](rowValue);
    }

    isRow = currentWorksheet.Cells[++i, 1].Value;
}
相关问题