有什么方法可以使它更通用吗?
Any way to make this more generic?
我有这两个功能,用于在层次结构中搜索文件夹:
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;
}
如您所见,它们彼此非常相似。我怎样才能重新构建它们,这样我就不会多次使用基本相同的代码,每次一个 属性 我可能想用它来找到它们?
创建一个带有执行逻辑的条件参数的方法:
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;
}
将您的 public Find
方法重写为:
public Folder<T> Find(string path) {
return Find(f => f.Path == path);
}
我有这两个功能,用于在层次结构中搜索文件夹:
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;
}
如您所见,它们彼此非常相似。我怎样才能重新构建它们,这样我就不会多次使用基本相同的代码,每次一个 属性 我可能想用它来找到它们?
创建一个带有执行逻辑的条件参数的方法:
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;
}
将您的 public Find
方法重写为:
public Folder<T> Find(string path) {
return Find(f => f.Path == path);
}