【发布时间】:2020-07-05 03:52:44
【问题描述】:
public class CategoryInModel
{
public int Id { get; set; }
public CategoryInModel Parent { get; set; }
}
我有一个像上面这样的课程。我想获得父对象的深度。
父对象可以有不同的深度。 喜欢:
父.父.父
或
父母.父母
如何找到父对象的深度?
【问题讨论】:
public class CategoryInModel
{
public int Id { get; set; }
public CategoryInModel Parent { get; set; }
}
我有一个像上面这样的课程。我想获得父对象的深度。
父对象可以有不同的深度。 喜欢:
父.父.父
或
父母.父母
如何找到父对象的深度?
【问题讨论】:
static int GetDepth (CategoryInModel cat, int depth = -1)
{
if (cat == null)
return depth;
else
return GetDepth(cat.Parent, depth + 1);
}
然后使用:
var mod = new CategoryInModel { Parent = new CategoryInModel { Parent = new CategoryInModel { Parent = new CategoryInModel() } } };
Console.WriteLine(GetDepth(mod));
【讨论】:
基于模型深度为 1 + 父级深度的逻辑:
public class CategoryInModel
{
public int Id { get; set; }
public CategoryInModel Parent { get; set; }
public int Depth => 1 + ParentDepth;
public int ParentDepth => Parent?.Depth ?? 0;
}
【讨论】: