简体   繁体   中英

Object within an object is null

I'm using C# and have created an object to send to a JSON service that looks like this:

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

I can code hint when setting the sub object:

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

But when the program is run, the sub-object itself is null (_req.value = null) and the two items under that object don't show.

Why is this happening?

You need to initialize the "value" to something.

Add this constructor to your SendRequest class:

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

You can use object initializers

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

at this point method is null

public string method { get; set; }

longer but what you can do is

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

value is just a bad name

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

or

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM