如何找到属性的深度?

问题描述 投票:0回答:2
public class CategoryInModel
{
 public int Id { get; set; }
 public CategoryInModel Parent { get; set; }
}

我有如上所述的课程。我想了解父对象的深度。

父对象可以具有各种深度。喜欢:

Parent.Parent.Parent

Parent.Parent

如何找到父对象的深度?

c# recursion hierarchy
2个回答
4
投票

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

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));
© www.soinside.com 2019 - 2024. All rights reserved.