【问题标题】:How to find depth of property?如何找到属性的深度?
【发布时间】:2020-07-05 03:52:44
【问题描述】:
public class CategoryInModel
{
 public int Id { get; set; }
 public CategoryInModel Parent { get; set; }
}

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

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

父.父.父

父母.父母

如何找到父对象的深度?

【问题讨论】:

    标签: c# recursion hierarchy


    【解决方案1】:
    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));
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2013-04-15
        • 2012-05-19
        • 2015-12-10
        • 1970-01-01
        • 2018-01-03
        • 2023-03-27
        • 2017-07-16
        • 1970-01-01
        • 2021-05-11
        相关资源
        最近更新 更多