NullReferenceException when trying to set class property

后端 未结 7 1698
醉酒成梦
醉酒成梦 2021-01-22 00:56

Basically I have 2 classes, \"Manifest\" and \"BrowserAction\", set out like this:

public class BrowserAction
{
    public string default_icon {get; set;}
    pu         


        
7条回答
  •  猫巷女王i
    2021-01-22 01:41

    You are accessing property browser_action of newly created instance newManifest that is still null.

    Change your example to something like:

    public void setManifest()
    {
        Manifest newManifest = new Manifest();
        newManifest.browser_action = new BrowserAction();
        newManifest.browser_action.default_popup = "popup.html";
    }
    

    I am assuming that BrowserAction has a public accessible constructor with no arguments.

    Or in one go:

    public void setManifest()
    {
        Manifest newManifest = new Manifest()
            {
                browser_action = new BrowserAction()
                    {
                        default_popup = "popup.html"
                    }
            };
    }
    

提交回复
热议问题