【问题标题】:Making one function instead of two制作一个功能而不是两个
【发布时间】:2016-02-24 21:20:23
【问题描述】:

我有两个功能:

public List<string> getAllProperties1()
{
    List<string> output = new List<string>();
    foreach (MyItem item in getItems())
    {
        if (!output.Contains(item.property1) &&
            item.property1 != null)
        {
            output.Add(item.property1);
        }
    }
    return output;
}

public List<string> getAllProperties2()
{
    List<string> output = new List<string>();
    foreach (MyItem item in getItems())
    {
        if (!output.Contains(item.property2) &&
            item.property2 != null)
        {
            output.Add(item.property2);
        }
    }
    return output;
}    

我重命名了函数、项和属性以使事情更简单。我想做的是一个功能,可能更简单——而不是这两个。如何做到这一点?

Property1 和Property 2 都是字符串属性。

【问题讨论】:

标签: c# function generics refactoring


【解决方案1】:

你真的需要方法吗:

List<string> allUniqueProp1 = getItems()
    .Select(x => x.property1)
    .Where(s => s != null)
    .Distinct()
    .ToList();

property2 也一样,你就完成了

【讨论】:

    【解决方案2】:

    代码:

    public List<string> getAllProperties(Func<MyItem, string> func)
    {
        List<string> output = new List<string>();
        foreach (MyItem item in getItems())
        {
            string value = func(item);
            if (!output.Contains(value) &&
                value != null)
            {
                output.Add(value);
            }
        }
        return output;
    }
    

    用法:

    getAllProperties(e => e.property1);
    

    【讨论】:

      【解决方案3】:

      使用 Func 作为策略来获取比较属性并从单个方法调用:

      public List<string> GetAll(Func<MyItem, string> propertyGetter)
      {
          List<string> output = new List<string>();
          foreach (MyItem item in getItems())
          {
              var value = propertyGetter(item);
              if (!output.Contains(value) && value != null)
              {
                  output.Add(value);
              }
          }
          return output;
      } 
      

      然后使用:

      GetAll(item => item.Property1);
      GetAll(item => item.Property2);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-03-09
        • 1970-01-01
        • 1970-01-01
        • 2017-11-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-03
        相关资源
        最近更新 更多