public class CategoryInModel
{
public int Id { get; set; }
public CategoryInModel Parent { get; set; }
}
我有如上所述的课程。我想了解父对象的深度。
父对象可以具有各种深度。喜欢:
Parent.Parent.Parent
或
Parent.Parent
如何找到父对象的深度?
基于模型深度为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;
}
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));