【问题标题】:C# Initializing nested classes and external class produces Null reference [duplicate]C#初始化嵌套类和外部类产生空引用[重复]
【发布时间】:2021-05-25 16:19:48
【问题描述】:

我有以下代码:

using System;
using System.Collections.Generic;

public class XTRAsystem
{
    public string version
    { get; set; }

    public XTRAapi api
    { get; set; }

    public XTRAsystem(string system_version)
    {
        this.version = system_version;
        XTRAapi api = new XTRAapi(Guid.NewGuid());
        Console.WriteLine("New XTRA system (" + this.version + ") initialized.");
    }

    public class XTRAapi
    {
        public Guid id
        { get; set; }

        public string name
        { get; set; }

        public XTRAapi(Guid Id)
        {
            this.id = Id;
            Console.WriteLine("New T24 API created.");
        }
    }
}

public class testCase
{
    public int caseNumber
    { get; set; }

    public List<string> data;

    public XTRAsystem refSystem
    { get; set; }

    public testCase()
    {
        data = new List<string>();
        Console.WriteLine("New Test Case created.");
    }
}

上面的两个类嵌套是有原因的。 现在,在我的 Main 程序中,下面的代码会产生 Null 引用异常。有人可以帮我吗?

using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Start..");

            XTRAsystem mySystem = new XTRAsystem("Mickey");
            testCase[] myTest = new testCase[100];

            Console.WriteLine("Capacity is {0}", myTest.Length);

            //  'Object reference not set to an instance of an object' for all the below
            myTest[0].caseNumber = 1;

            myTest[0].data.Add("first test");
            myTest[0].data.Add("second test");
            myTest[0].data.Add("third test");

            myTest[0].refSystem = mySystem;
        }
    }
}

根据您的专业知识和经验,有没有其他方法可以产生现在产生错误的功能(行 myTest[0]... 等) 非常感谢

【问题讨论】:

    标签: c# class compiler-errors nested


    【解决方案1】:

    您必须先初始化每个数组项,然后才能使用属性

    testCase[] myTest = new testCase[100];
    
    Console.WriteLine("Capacity is {0}", myTest.Length);
    myTest[0] = new testCase();
               
    myTest[0].caseNumber = 1;
    
    // also, initialize your list
    myTest[0].data = new List<string>();
    

    【讨论】:

    • 非常感谢!最后一件事:在 testCase 构造函数data = new List&lt;string&gt;(); 中初始化数据列表的目的是什么,如果我必须(再次)在外部为每个新的 testCase 初始化它?
    • 创建类型和初始化变量是两件不同的事情。您可以在类中初始化数据数组,但必须这样做。在您的 testCase 类中,将数据初始化更改为此 public List&lt;string&gt; data = new List&lt;string&gt;();。这样当你初始化数组元素时它就被初始化了。
    • 非常感谢您的宝贵时间和宝贵意见。我会按照你的建议去做,并从构造函数中删除该行,没有任何意义。非常感谢!
    • 实际上,请注意:如果我在属性 (public Some thing {get; set;} = new Some();) 旁边进行初始化,然后在类的构造函数中进行初始化,thing 将被初始化两次。所以,有人应该在属性之后初始化或者或者在构造函数中初始化,而不是两次。感谢您展示这个概念。
    • 正确。如果列表未在构造函数中初始化,则只需要初始化列表。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-13
    • 2016-08-08
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多