NullReferenceException when trying to set class property

后端 未结 7 1690
醉酒成梦
醉酒成梦 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条回答
  • 2021-01-22 01:34

    You've initialised newManifest, but browser_action is still null (presumably).

    You are then trying to set default_popup on the null browser_action and getting the exception

    newManifest.browser_action.default_popup = "popup.html";

    0 讨论(0)
  • 2021-01-22 01:38

    Default value for reference-type object is null. You need to create BrowserAction instance on browser_action property before using it.

    // Create Manifest instance
    Manifest newManifest = new Manifest();
    
    Console.Writeline (newManifest.browser_action == null); // Print true;
    
    // Instantiate BrowserAction on browser_action property
    newManifest.browser_action = new BrowserAction();
    
    Console.Writeline (newManifest.browser_action == null); // Print false;
    
    // Now you can use browser_action property
    newManifest.browser_action.default_popup = "popup.html";
    
    0 讨论(0)
  • 2021-01-22 01:40

    I think the Manifest.browser_action property returns null because you don't initialize it. Create an object before accessing its properties:

    Manifest newManifest = new Manifest();
    newManifest.browser_action = new BrowserAction();
    newManifest.browser_action.default_popup = "popup.html";
    
    0 讨论(0)
  • 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"
                    }
            };
    }
    
    0 讨论(0)
  • 2021-01-22 01:50

    browser_action has not been initialized. Add a parameterless constructor to your Manifest class like this:

    public class Manifest
    {
        public Manifest()
        {
               this.browser_action = new BrowswerAction;
        }
    
        public BrowserAction browser_action {get; set;}
    }
    
    0 讨论(0)
  • 2021-01-22 01:52

    You'll have to intialize browser_action too before accessing properties on that instance.

    newManifest.browser_action= new BrowserAction();
    
    0 讨论(0)
提交回复
热议问题