我可以为匿名类型属性分配空值吗?

时间:2014-07-20 15:19:44

标签: c#

我在WebAPI中有以下内容,它被转换为JSON字符串并发送到客户端:

return Ok(new
    {
        Answer = "xxx",
        Text = question.Text,
        Answers = question.Answers.Select((a, i) => new
        {
            AnswerId = a.AnswerId,
            AnswerUId = i + 1,
            Text = a.Text
        })
    });

现在我意识到我想将值null赋给Answer。但是这给了我一条消息说

cannot assign <null> to anonymous type property. 

有没有办法我可以这样做,而不必定义一个类,所以我可以分配null?

1 个答案:

答案 0 :(得分:55)

绝对 - 您只需要将null值转换为正确的类型,以便编译器知道您想要该属性的类型。例如:

return Ok(new {
    Answer = (string) null,
    Text = ...,
    ...
});