用c#修改类

本文关键字:修改 | 更新日期: 2023-09-27 18:01:08

我有下表

 PNLId  PNLParentId Operator    Sign    DisplayingOrder    PNLGrpId
     0        0         ~            1         1            1
     1       105        +           1         1            2
    11       20         +           -1        1            5

我使用类Node来获取表中的父/子

class Node
{
    public int Id { get; set; }
    public int? ParentId { get; set; }
    public string Operator { get; set; }
    public Node Parent { get; set; }
    public IList<Node> Children { get; set; }
    public Node()
    {
        Children = new List<Node>();
    }
    public override string ToString()
    {
        return "Node: " + Operator + " " + Id + " " 
            + string.Join(",", Children.Select(x => x.Id));
    }
}

我得到了以下结果

[50 Node: + 50 36,37]
[51 Node: + 51 49,50]
[52 Node: + 52 20,21,22]
[69 Node: + 69 56,57,58,59]

我如何修改类节点以使子节点成对(Sign,child(,类似

[50 Node: + 50 (-1,36),(1,37)]
[51 Node: + 51 (-1,49),(-1,50)]
[52 Node: + 52 (1,20),(-1,21),(-1,22)]
[69 Node: + 69 (-1,56),(-1,57),(1,58),(1,59)]

用c#修改类

实现ToString,如下所示:

return "Node: " + Operator + " " + Id + " " + 
       string.Join(",", Children.Select
                         (x => string.Format("({0},{1})", x.Sign, x.Id)));

为了您的确切目的,请考虑以下步骤:

  • 步骤1-将Sign属性添加到类

    class Node
    {
        public int Id { get; set; }
        public int? ParentId { get; set; }
        public string Operator { get; set; }
        public Node Parent { get; set; }
        public IList<Node> Children { get; set; }
        // HERE WE GO
        public int Sign { get; set; }
        ...
    }
    
  • 步骤2-确定标题为"the following"的表和Node类之间的连接。代码中的确切位置规定Id属性为。NET中PNLId列的表现形式?

  • 步骤3-一旦回答了步骤2的问题,您必须为Sign属性重新创建相同的效果。。Sign列关系

  • 步骤4-更改ToString方法,如下所示:

    class Node
    {
        ...
        public override string ToString()
        {
            return "Node: " + Operator + " " + Id + " " 
                + string.Join(",", Children.Select(x => string.Format("({0}, {1})", x.Sign, x.Id)));
        }
    

    }

注意:检查Children.Select lambda参数的修改:

Children.Select(x => string.Format("({0}, {1})", x.Sign, x.Id))