简体   繁体   English

C#多级对象和列表访问

[英]C# multi level object and list access

I have no idea what should this question be titled nor keyword to search. 我不知道这个问题的标题是什么,也不知道搜索的关键字。

Scenario : I have a model as below 场景 :我有一个模型如下

public class Message { public List<Page> Pages { get; set; }
public class Page { public List<Line> Lines { get; set; }
public class Line { public string Text {get; set; }

When I wanted to insert a Line with Text = "Test" at Page 1, I would need to do the following. 当我想在Page 1 Page插入带有Text = "Test"Line时,我需要执行以下操作。

var Message = new Message();
var line = new Line { Text = "Test" };
var page = new Page();
page.Lines.Add(line);
Message.Pages.Add(page);

Question : are there any easier way to achieve this? 问题 :有没有更简单的方法来实现这一目标? Eg. 例如。

Message.Pages[0].Lines[0].Text = "Test";

Thanks. 谢谢。

Edit : Assumed all properties are properly instantiated in constructors. 编辑 :假设所有属性都在构造函数中正确实例化。

var msg = new Message {
    Pages = new List<Page> {
        new Page {
            Lines = new List<Line> { new Line { Text = "Test" } }
        }
    }
};

Note: if the lists are initialized in their respective constructors, you can remove the new List<> bits: 注意:如果列表在各自的构造函数中初始化,则可以删除new List<>位:

var msg = new Message {
    Pages = {
        new Page {
            Lines = { new Line { Text = "Test" } }
        }
    }
};

You could also add an implicit conversion operator from string to Line , in which case: 您还可以将一个隐式转换运算符从string添加到Line ,在这种情况下:

var msg = new Message {
    Pages = {
        new Page {
            Lines = { "Test" }
        }
    }
};

Edit: fully working example, including operator and ctor initialization, and multiple pages (see comments): 编辑:完整的工作示例,包括操作符和ctor初始化,以及多个页面(请参阅注释):

using System.Collections.Generic;

public class Message {
    public List<Page> Pages { get; private set; }
    public Message() { Pages = new List<Page>(); }
}
public class Page {
    public List<Line> Lines { get; private set; }
    public Page() { Lines = new List<Line>(); }
}
public class Line {
    public string Text { get; private set; }
    public static implicit operator Line(string value) {
        return new Line { Text = value };
    }
}

static class Program {
    static void Main() {
        var msg = new Message {
            Pages = {
                new Page {
                    Lines = { "Test" }
                },
                new Page {
                    Lines = {
                        "On another page",
                        "With two lines"
                    },
                }
            }
        };
    }
}

You can create helper methods in your classes, which will provide handy API for building messages and pages. 您可以在类中创建辅助方法,这将为构建消息和页面提供方便的API。 First is Message class - new Add method accepts page to add, and returns message instance. 首先是Message类 - 新的Add方法接受要添加的页面,并返回消息实例。 That will allow to use fluent API for adding pages (example at the bottom): 这将允许使用流畅的API来添加页面(示例在底部):

public class Message
{
    public Message()
    {
        Pages = new List<Page>();
    }

    public List<Page> Pages { get; private set; }

    public Message Add(Page page)
    {
       Pages.Add(page);
       return this;
    }
}

And page class. 和页面类。 I added static creation method, which builds page with any number of lines you pass to this method: 我添加了静态创建方法,它使用传递给此方法的任意数量的行构建页面:

public class Page 
{
    public Page() 
    {
        Lines = new List<Line>();
    }

    public List<Line> Lines { get; private set; }

    public static Page WithLines(params string[] texts)
    {
        var page = new Page();

        foreach(var text in texts)
           page.Lines.Add(new Line { Text = text });

        return page;
    }
}

Then adding page with lines will look like 然后添加带有行的页面看起来像

message.Add(Page.WithLines("Text1", "Text2"))
       .Add(Page.WithLines("Text3"));

What Marc and Sergey said. 马克和谢尔盖说的话。 Also you can consider a simplified builder. 您也可以考虑使用简化的构建器。 I replaced the properties with fields to make the example smaller: 我用字段替换了属性以使示例更小:

public class Message { public List<Page> Pages = new List<Page>(); }
public class Page { public List<Line> Lines = new List<Line>(); }
public class Line { public string Text; }

Then your builder would look something like this: 那么你的构建器看起来像这样:

public class Typewriter
{
    Message message = new Message();
    Page currentPage;

    public Typewriter NewPage()
    {
        currentPage = new Page();
        message.Pages.Add(currentPage);
        return this;
    }

    public Typewriter AddLine(string text)
    {
        currentPage.Lines.Add(new Line() { Text = text });
        return this;
    }
}

Then you can do: 然后你可以这样做:

var typewriter = new Typewriter();
typewriter.NewPage().AddLine("First line on first page")
    .AddLine("Next line on first page")
    .NewPage().AddLine("Next page etc");

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

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