首页 > 解决方案 > 如何找到属性的深度?

问题描述

public class CategoryInModel
{
 public int Id { get; set; }
 public CategoryInModel Parent { get; set; }
}

我有一个像上面这样的课程。我想获得父对象的深度。

父对象可以有不同的深度。喜欢:

父.父.父

或者

父.父

如何找到父对象的深度?

标签: c#recursionhierarchy

解决方案


基于模型深度为 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;
}

推荐阅读