2016-01-08 201 views
2

我使用C#和已经创建了一个对象发送一个JSON的服务,看起来像这样:对象为空

public class SendRequest 
{ 
    public string id { get; set; } 
    public string case { get; set; } 
    public string method { get; set; } 
    public Volume value { get; set; } 
} 

public class Volume 
{ 
    public int level; 
    public bool mute; 
} 

设置子对象的时候,我可以代码提示:

var _req = new SendRequest(); 
_req.value.mute = false; 
_req.value.level = 50; 

但是,当程序运行时,子对象本身为空(_req.value = null),并且该对象下的两个项目不显示。

这是怎么发生的?

+0

所以它不存在 – scrappedcola

+0

你需要分配一个新的你还没有创建一个卷对象的实例'音量“对象到”值“。 – juharr

+0

你能展示你的json吗? – RredCat

回答

5

您需要初始化“值”。

此构造函数添加到您的sendRequest将类:

public SendRequest(){ value = new Volume(); } 
2

您可以在此点方法使用object initializers

var _req = new SendRequest() 
{ 
    value = new Volume() 
    { 
     mute = false, 
     level = 50, 
    }, 
}; 
-1

是空

public string method { get; set; } 

长,但你可以做的是

private string method = string.empty; 
public string Method { get {return method;} set {method = value;} } 

值仅仅是一个不好的名字

private Volume volume = new Volume(); 
public Volume Volume { get {return volume;} set {volume = value;} } 

volume = new Volume (mute = false, value.level = 50); 
+0

来吧投票是什么问题。这工作。 – Paparazzi

+0

这是如何解决问题的? – dotctor

+0

@dotctor变量在初始化之前为空。所以我需要用体积拼出来? – Paparazzi