You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

类中含结构体整数数组时的空引用异常排查

问题原因及解决方案

核心问题分析

当tsTABLE为结构体(struct)时

C#中值类型数组初始化时,会使用编译器自动生成的默认无参构造初始化每个元素,这个构造只会将所有字段设为默认值(引用类型字段设为null),不会执行你自定义的字段初始化器或自定义无参构造。所以数组里的每个tsTABLE实例的C字段都是null,触发空引用错误。

另外你自定义的tsTABLE无参构造里没有对C做初始化,就算手动调用这个构造,C依然是null。

当tsTABLE改为类(class)时

引用类型数组创建后,每个元素的默认值是null,你没有实例化数组里的每个tsTABLE对象,直接访问C自然会触发空引用错误。

修复方案

方案1:保持tsTABLE为结构体

修改代码,确保每个tsTABLE实例都通过自定义构造完成初始化:

public class sInfo
{
    public int A { get; set; }
    public int B { get; set; }
    public tsTABLE[] Tables;

    public sInfo()
    {
        Tables = new tsTABLE[4];
        // 手动实例化每个结构体元素,触发自定义构造
        for (int i = 0; i < Tables.Length; i++)
        {
            Tables[i] = new tsTABLE();
        }
    }
}

public struct tsTABLE
{
    public int[] C;
    public int Count { get; set; }                    

    public tsTABLE()
    {
        // 在构造函数中初始化数组
        C = new int[6] { 0, 1, 2, 3, 4, 5 };
        Count = 0;
    }
}

方案2:将tsTABLE改为类

必须手动实例化数组中的每个类对象:

public class sInfo
{
    public int A { get; set; }
    public int B { get; set; }
    public tsTABLE[] Tables;

    public sInfo()
    {
        Tables = new tsTABLE[4];
        // 实例化每个类对象
        for (int i = 0; i < Tables.Length; i++)
        {
            Tables[i] = new tsTABLE();
        }
    }
}

public class tsTABLE
{
    public int[] C = new int[6] { 0, 1, 2, 3, 4, 5 };
    public int Count { get; set; }                    
}

内容的提问来源于stack exchange,提问作者user3119168

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 04:27:15