尝试设置类属性时出现 NullReferenceException

NullReferenceException when trying to set class property(尝试设置类属性时出现 NullReferenceException)
本文介绍了尝试设置类属性时出现 NullReferenceException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我有 2 个类,Manifest"和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;}
}

问题是,当我尝试设置 Manifest 类的 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)