访问数组时出现空引用错误

发布于 2024-10-14 17:51:26 字数 275 浏览 4 评论 0原文

我有以下类:

public class MyClass
{
   public MyArrObj[] arrOfObj; //Array of objects
}

当我尝试使用以下方式访问它时:

MyClass myClass = new MyClass;
myClass.arrOfObj = GetData();

它给了我一个空异常。如果它不是一个数组,我可以新建它,但我不知道如何处理这个问题。

I have the following class:

public class MyClass
{
   public MyArrObj[] arrOfObj; //Array of objects
}

When I try to access it using:

MyClass myClass = new MyClass;
myClass.arrOfObj = GetData();

it gives me a null exception. If it wasn't an array, I could have new'd it, but i am not sure how to handle this.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

ゝ杯具 2024-10-21 17:51:26

创建引用类型的数组(在您的情况下是 MyArrObj)时,除了分配内存之外,还需要为每个数组元素分配内存(使用 new 运算符)对于数组本身。

引用类型数组

例如,如果您创建 MyArrObj 数组,

MyArrObj[] objectArray = new MyArrObj[3];

则数组元素 objectArray[0]objectArray[2] 仍将为 null。需要单独初始化。

objectArray[0] = new MyArrObj();

只有完成上述步骤后,才能访问数组元素的成员。

objectArray[0].SomeMethod();
SomePropertyType readProperty = objectArray[0].SomeProperty;

如果跳过数组元素初始化,则尝试访问数组元素的成员将给出 <代码>System.NullReferenceException

objectArray[0].SomeMethod(); // throws NullReferenceException

因为
对象数组[0];null

来检查这一点

if(objectArray[0] == null)
{
    Console.WriteLine("objectArray[0] is null");
}

您可以使用值类型数组

如果您事先知道数组,那么您可以使用@cloked指出的初始化。

对于内置类型等值类型(例如 int、float、结构体等),您无需初始化每个数组元素。
例如,如果您创建一个 int 数组,

int[] intArray = new int[3];

那么数组元素 intArray[0]intArray[2] 就分配了内存,并且可以将值分配给他们。

intArray [0] = 1;

检查您的 GetData()

因此,您的 GetData() 方法应包含如下代码:

private MyArrObj[] GetData()
{
    int numberOfObjects = GetNumberOfObjects(); // Get the number of objects at runtime

    MyArrObj[] objectArray = new MyArrObj[numberOfObjects];

    for (int i = 0; i < numberOfObjects; i++)
    {
        objectArray[i] = new MyArrObj();
    }

    return objectArray;
}

更多信息

When creating an array of a reference type (MyArrObj in your case), it is required that you allocate memory for each array element (using new operator) in addition to allocating memory for the array itself.

Array of Reference types

For example, if you create an MyArrObj array,

MyArrObj[] objectArray = new MyArrObj[3];

Then the array elements objectArray[0] to objectArray[2] would still be null. A separate initialization is required.

objectArray[0] = new MyArrObj();

Only when the above step is done can you access the members of the array element.

objectArray[0].SomeMethod();
SomePropertyType readProperty = objectArray[0].SomeProperty;

If you skip the array element initialization then trying to access a member of the array element would give a System.NullReferenceException

objectArray[0].SomeMethod(); // throws NullReferenceException

because
objectArray[0]; is null.

You can check this using

if(objectArray[0] == null)
{
    Console.WriteLine("objectArray[0] is null");
}

Array of Value types

If you know the array before hand, then you can use the initialization pointed out by @clonked.

For value types like built in types(like int, float, structs, etc. you need not initialize each array element.
For example, if you create an int array,

int[] intArray = new int[3];

Then the array elements intArray[0] to intArray[2] have the memoery allocated and values can be assigned to them.

intArray [0] = 1;

Check your GetData()

So your GetData() method should include code like this,

private MyArrObj[] GetData()
{
    int numberOfObjects = GetNumberOfObjects(); // Get the number of objects at runtime

    MyArrObj[] objectArray = new MyArrObj[numberOfObjects];

    for (int i = 0; i < numberOfObjects; i++)
    {
        objectArray[i] = new MyArrObj();
    }

    return objectArray;
}

More information

錯遇了你 2024-10-21 17:51:26

您使用 GetData() 方法的方式,它必须返回一个数组。

这里有几种动态创建数组的方法(不过,您仍然需要填充它们):

int[] x = new int[5] ; // create a 5-element  array of integers
int[] y = (int[]) Array.CreateInstance(typeof(int),5) ; // create a 5 element array of integers

干杯。

The way your are using your GetData() method, it has to return an array.

Here's a couple of ways to create an array on the fly (you'll still need to populate them, though):

int[] x = new int[5] ; // create a 5-element  array of integers
int[] y = (int[]) Array.CreateInstance(typeof(int),5) ; // create a 5 element array of integers

Cheers.

濫情▎り 2024-10-21 17:51:26

您需要做这样的事情:

class Program
    {
        static void Main(string[] args)
        {
            MyClass myClass = new MyClass();
            myClass.arrOfObj = GetData();
            foreach (var item in myClass.arrOfObj)
            {
                Console.WriteLine(item.ToString());
            }

        Console.ReadLine();

    }

    private static int[] GetData()
    {
        return new int[]{1,2,3,4,5};
    }
}

public class MyClass
{
    public int[] arrOfObj; //Array of objects
}

GetData 方法是重要的部分。
它必须初始化一个新数组并返回它。

You need to do something like this:

class Program
    {
        static void Main(string[] args)
        {
            MyClass myClass = new MyClass();
            myClass.arrOfObj = GetData();
            foreach (var item in myClass.arrOfObj)
            {
                Console.WriteLine(item.ToString());
            }

        Console.ReadLine();

    }

    private static int[] GetData()
    {
        return new int[]{1,2,3,4,5};
    }
}

public class MyClass
{
    public int[] arrOfObj; //Array of objects
}

the GetData method is the important part.
it has to initialize a new array and return it.

违心° 2024-10-21 17:51:26

如果您的 GetData() 方法的签名类似于 public MyArrObj[] GetData() 那么您的代码应该可以正常工作。我使用 2 个版本的“GetData”方法测试了您的代码:

public MyArrObj[] GetData()
{
    return new MyArrObj[3] { new MyArrObj(), new MyArrObj(), new MyArrObj() };
}

public MyArrObj[] GetData2()
{
    return new MyArrObj[0];
}

这些方法都没有引发空引用异常。我怀疑您的 GetData() 方法内部还有其他东西抛出空引用,而不是将该方法的结果分配给 arrOfObj 字段的操作。

If the signature of your GetData() method looks like public MyArrObj[] GetData() then your code should work correctly. I tested your code with 2 versions of the 'GetData' method:

public MyArrObj[] GetData()
{
    return new MyArrObj[3] { new MyArrObj(), new MyArrObj(), new MyArrObj() };
}

public MyArrObj[] GetData2()
{
    return new MyArrObj[0];
}

Neither of these methods threw a null reference exception. I would suspect there is something else inside of your GetData() method that is throwing the null reference, rather than the operation of assigning the results of that method to the arrOfObj field.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文