繁体   English   中英

C#动态对象列表

[英]C# Dynamic list of objects

我有一个小实体“类别”

Id
Name 
Parent_id

我想用该项目所有父母的字符串覆盖ToString(),我不知道该项目有多少父母。

Example: (pseudo code)
Item1 =>  Id = 1, Name = Computers, Parent_id = null 
Item2 =>  Id = 2, Name = Laptops  , Parent_id = 1
Item3 =>  Id = 3, Name = Acer     , Parent_id = 2

在Item3.ToString()的输出上,我希望结果为"Computers > Laptops > Acer" 而且我需要它是动态的,所以我不知道它应该采取多少步骤...任何新想法?

您需要递归执行此操作:

public overrides string ToString()
{
    string build = parent.ToString();
    if (!String.IsNullOrEmpty(build)) build += " > ";
    build += Name;
    return build
}

可以按照上述方法进行操作-每个实体都将在其父对象上调用ToString,以便获得层次结构中所有实体的列表。 无论层次结构深入到何种程度(在合理的范围内),这都将起作用。

注意:您需要引用父对象才能执行此操作,或者可以使用属性,也可以使用已获得的parentid属性来查找实体。

首先,您需要将父项本身(而不仅仅是ID)添加到每个项中,然后通过简单的循环就足够简单了:

public override string ToString()
{
    List<string> names = new List<string>();
    names.Add(this.Name);
    Category parent = this.Parent;
    while (parent != null)
    {
        names.Add(parent.Name);
        parent = parent.Parent;
    }
    names.Reverse();
    return string.Join(" > ", names);
}
public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Category Parent { get; set; }

    public override string ToString()
    {
        return Parent == null 
            ? Name
            : string.Format("{0} > {1}", Parent, Name);
    }
}

用法:

item1 = new Category{Id = 1, Name = "Computers"};
item2 = new Category{Id = 2, Name = "Laptops", Parent = item1};
item3 = new Category{Id = 3, Name = "Acer", Parent = item2};

Debug.Print(item3.ToString());
Debug.Print(item2.ToString());
Debug.Print(item1.ToString());

结果:

Computers > Laptops > Acer
Computers > Laptops
Computers

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM