Skip to main content
 首页 » 编程设计

c#之使用初始化器访问对象的属性

2024年02月13日15lyhabc

我有这个代码:

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" 
    } 
};