我正在尝试以下方法:
public class ResultDTO
{
public int Id { get; set; }
public string Text { get; set; }
public int AnswerId { get; set; }
public string AnswerText { get; set; }
}
List<ResultDTO> result1 = new List<ResultDTO> () {
new ResultDTO () { Id:1, Text: "abc", AnswerId: "1", AnswerText: "Aab1" },
new ResultDTO () { Id:1, Text: "abc", AnswerId: "2", AnswerText: "Aab2" },
new ResultDTO () { Id:1, Text: "abc", AnswerId: "3", AnswerText: "Aab3" },
new ResultDTO () { Id:1, Text: "def", AnswerId: "4", AnswerText: "Aab4" },
new ResultDTO () { Id:1, Text: "def", AnswerId: "5", AnswerText: "Aab5" },
new ResultDTO () { Id:1, Text: "def", AnswerId: "6", AnswerText: "Aab6" }
}
这在IDE中给出了很多语法错误。有人可以告诉我做错了吗?
答案 0 :(得分:3)
这不是JSon对象和数组。可以使用=
运算符分配属性。
List<ResultDTO> result1 = new List<ResultDTO> () {
new ResultDTO () { Id=1, Text= "abc", AnswerId= 1, AnswerText= "Aab1" },
....
}
我建议你创建一个具有属性参数的构造函数;
public class ResultDTO
{
public int Id { get; private set; }
public string Text { get; set; }
public int AnswerId { get; set; }
public string AnswerText { get; set; }
public ResultDTO(int id, string _text, int ansId, string ansText)
{
Id=id;
Text = _text;
AnswerId = ansId;
AnswerText = ansText;
}
}
然后像这样初始化列表。
List<ResultDTO> result1 = new List<ResultDTO> () {
new ResultDTO (1,"abc",1,"Aab1"),
new ResultDTO (1,"abc",2,"Aab2"),
new ResultDTO (1,"abc",3,"Aab3"),
....
}
当您只读指定属性时,这将为您提供一些优势。看看上面的类我声明Id
属性是公开可读的,不能在课堂上设置。
答案 1 :(得分:2)
初始化类时,需要使用=而不是:
public class ResultDTO
{
public int Id { get; set; }
public string Text { get; set; }
public int AnswerId { get; set; }
public string AnswerText { get; set; }
}
List<ResultDTO> result1 = new List<ResultDTO> () {
new ResultDTO () { Id=1, Text= "abc", AnswerId= 1, AnswerText= "Aab1" },
new ResultDTO () { Id=1, Text= "abc", AnswerId= 2, AnswerText= "Aab2" },
new ResultDTO () { Id=1, Text= "abc", AnswerId= 3, AnswerText= "Aab3" },
new ResultDTO () { Id=1, Text= "def", AnswerId= 4, AnswerText= "Aab4" },
new ResultDTO () { Id=1, Text= "def", AnswerId= 5, AnswerText= "Aab5" },
new ResultDTO () { Id=1, Text= "def", AnswerId= 6, AnswerText= "Aab6" }
}