尝试设置类属性时发生NullReferenceException [英] NullReferenceException when trying to set class property

查看:95
本文介绍了尝试设置类属性时发生NullReferenceException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我有2个类,清单"和"BrowserAction",如下所示:

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

public class BrowserAction
{
    public string default_icon {get; set;}
    public string default_title {get; set;}
    public string default_popup {get; set;}
}


public class Manifest
{
    public BrowserAction browser_action {get; set;}
}

问题是,当我尝试设置清单类的browser_action.default_popup的实例时,如下所示:

The problem is, that when I try to set an instance of the Manifest class' browser_action.default_popup, like this:

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

我得到一个System.NullReferenceException.我环顾四周,但似乎找不到问题所在.对于"Manifest"类的其他属性(如字符串等),它可以很好地工作.

I get a System.NullReferenceException. I've looked around but I can't seem to find what the problem is. It works fine for other properties of the "Manifest" class that are just strings etc.

如果需要的话,我的IDE是MonoDevelop 2.4,而我的框架是Mono 2.6.7.

If it's relevant, my IDE is MonoDevelop 2.4, with Mono 2.6.7 for my framework.

推荐答案

在访问该实例的属性之前,您还必须初始化browser_action.

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

newManifest.browser_action= new BrowserAction();

这篇关于尝试设置类属性时发生NullReferenceException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆