NullReferenceException when trying to set class property(尝试设置类属性时出现 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:尝试设置类属性时出现 NullReferenceException
				
        
 
            
        - 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
 - MoreLinq maxBy vs LINQ max + where 2022-01-01
 - WebMatrix WebSecurity PasswordSalt 2022-01-01
 - 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
 - C#MongoDB使用Builders查找派生对象 2022-09-04
 - 如何用自己压缩一个 IEnumerable 2022-01-01
 - 输入按键事件处理程序 2022-01-01
 - Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
 - C# 中多线程网络服务器的模式 2022-01-01
 - 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
 
						
						
						
						
						
				
				
				
				