我有一个类似下面的课程
public class HintQuestion
{
public string QuestionCode { get; set; }
public string QuestionName { get; set; }
}
和下面的另一个问题
public class User
{
public User()
{
HintQuestion = new HintQuestion();
}
public HintQuestion HintQuestion { get; set; }
}
问题是当我创建User
calss的实例并将值赋给内部类对象时它无效。我正在使用对象初始化
User u=new user{HintQuestion.QuestionCode ="",...
但是当我创建构造函数时,它工作正常。
答案 0 :(得分:4)
使用对象初始化程序,您必须以与构造函数中相同的方式设置User.HintQuestion
属性,为其分配HintQuestion
对象,您也可以使用初始化程序创建该对象:
User u = new User {
HintQuestion = new HintQuestion { QuestionCode = "", QuestionName = "" }
};
答案 1 :(得分:4)
public class HintQuestion
{
public string QuestionCode { get; set; }
public string QuestionName { get; set; }
}
public class User
{
public User()
{
this.HintQuestion = new HintQuestion();
}
public HintQuestion HintQuestion { get; set; }
}
User u = new User { HintQuestion = new HintQuestion { QuestionCode = "test", QuestionName = "test1" } };