簡體   English   中英

如何找到屬性的深度?

[英]How to find depth of property?

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

我有一個類似上面的類。 我想獲得父對象的深度。

父對象可以有不同的深度。 喜歡:

父.父.父

或者

父.父

如何找到父對象的深度?

基於模型深度為 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));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM