有什么方法可以使它更通用吗?

时间:2015-07-08 10:54:20

标签: c# coding-style dry

我有这两个函数,用于搜索层次结构中的文件夹:

public Folder<T> Find (string Path)
  {
  Folder<T> Result = null;

  if (this.Path != Path &&
      ChildrenDict != null)
    {
    foreach (KeyValuePair<long, Folder<T>> Child in ChildrenDict)
      {
      Result = Child.Value.Find (Path);
      }
    }

  else
    {
    Result = this;
    }

  return Result;
  }

public Folder<T> Find (long ID)
  {
  Folder<T> Result = null;

  if (this.ID != ID &&
      ChildrenDict != null)
    {
    foreach (KeyValuePair<long, Folder<T>> Child in ChildrenDict)
      {
      Result = Child.Value.Find (ID);
      }
    }

  else
    {
    Result = this;
    }

  return Result;
  }

如你所见,它们彼此非常相似。我怎样才能重新构造它们,所以我几次没有基本相同的代码,每个属性一个我可能想用来找到它们?

1 个答案:

答案 0 :(得分:1)

创建一个带有条件参数的方法,该参数执行逻辑:

protected Folder<T> Find(Func<Folder<T>, bool> condition) {
    Folder<T> Result = null;
    if(!condition(this) && ChildrenDict != null) {
        foreach(var Child in ChildrenDict) {
            Result = Child.Value.Find(condition);
        }
    } else {
        Result = this;
    }
    return Result;
}

将您的公开Find方法重写为:

public Folder<T> Find(string path) {
   return Find(f => f.Path == path);
}