如何重构一组丑陋的 if 语句?

How can I refactor a set of ugly if statements?

我有这组 If 语句,它工作正常但看起来有点难看。有什么办法可以让它变得更好,而不是使用丑陋的 if 语句吗?问题是它使用 string.contains 这使得实现字典有点困难,我尝试过但失败了:(

这里是:

foreach (var Item in Stuff)
            {
                var loweredQuoteItem = quoteItem.Name.ToLower();

                if (loweredQuoteItem.Contains("one"))
                    Item.InsurerNameShort = "Item One";

                if (loweredQuoteItem.Contains("two"))
                    Item.InsurerNameShort = "Item Two";

                if (loweredQuoteItem.Contains("chaucer"))
                    Item.InsurerNameShort = "Chaucer";

                if (loweredQuoteItem.Contains("three"))
                    Item.InsurerNameShort = "Item Three";

                if (loweredQuoteItem.Contains("four"))
                    Item.InsurerNameShort = "Item Four";

                if (loweredQuoteItem.Contains("five"))
                    Item.InsurerNameShort = "Item Five";

               }

The problem is that it uses string.contains which makes it a bit difficult to implement a dictionary, which I tried and failed :(

那我猜你实现的不对。这是你应该做的:

  • 构建字典。
  • 将 "Item One" 作为键的值 "one"
  • 将 "Item Two" 作为键的值 "two"
  • 将 "Item Two" 作为键的值 "chaucer"
  • 等...
  • 在您当前的循环中,一旦您有了 loweredQuoteItem,就在您的词典上循环。
    • 如果字典包含 innerLoopKey,请将 Item.InsurerNameShort 设置为 innerLoopValue(并可选择中断)

确保在 foreach (var Item in Stuff) 循环之外构造此词典,以获得更好的性能。

为了简化您的方法,您可以使用内部 Action。这样你的方法看起来像这样

        Action<string,string, Action> method = (source, search, action) => {if (source.Contains(search)) action(); };
        method(loweredQuoteItem, "one", () => Item.InsurerNameShort = "Item One");
        method(loweredQuoteItem, "two", () => Item.InsurerNameShort = "Item Two");
        method(loweredQuoteItem, "chaucer", () => Item.InsurerNameShort = "Item Chaucer");

如果没有 lambda 并且您的逻辑真的很简单,那么您可以将 IF 语句移到不同的方法中:

    public void SetValueIfContains(string source, string search, string value, MyClass item)
    {
        if (source.Contains(search))
        {
            item.InsurerNameShort = value;
        }
    }

    public void YourFunction()
    {
        var loweredQuoteItem = quovteItem.Name.ToLower();
        SetValueIfContains(loweredQuoteItem, "one", "Item One", Item);
        SetValueIfContains(loweredQuoteItem, "two", "Item Two", Item);
        SetValueIfContains(loweredQuoteItem, "Chaucer", "Item chaucer", Item);
    }

如果 IF 语句中的逻辑很复杂,您可以定义 ISrategy 接口并针对每种情况实施策略。这是更多的最佳实践。