使用初始化程序访问对象的属性

本文关键字:对象 属性 访问 程序 初始化 | 更新日期: 2023-09-27 17:58:19

我有这个代码:

public class TopTen
{
    public int Id { get; set; }
    public string ShortDesc { get; set; }
    public string LongDesc { get; set; }
    public Image Photo { get; set; }
}
public class Image
{
    public string ImgUrl { get; set; }
    public string AlterText { get; set; }
}

我可以这样做来分配值:

new topten()
{
/*
     here I can access and give values to my properties. BUT i cant
     access and give values to the properties in my `Image` class.
     This is a problem because I would like to upload the new object as a json-file.
     So how do I access the properties in `Image`?
*/
}

使用初始化程序访问对象的属性

var x = new TopTen
{
    Id = 1,
    Photo = new Image
    {
       ImgUrl = "pic.jpg",
       AlterText = "This is a picture"
    }
};