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

向Dictionary<char,Tuple<int,int>>赋值时遇对象引用未设置实例错误求助

空引用异常解决方法

错误原因

你只声明了Dictionary<char, Tuple<int, int>>类型的变量keyCoords,但没有实例化它。此时keyCoords的值为null,尝试对null对象执行赋值操作就会触发"The object reference was not set to an object instance"错误。

解决步骤

1. 实例化Dictionary

有两种常用初始化方式:

  • 直接在声明时初始化:
private Dictionary<char, Tuple<int, int>> keyCoords = new Dictionary<char, Tuple<int, int>>();
  • 或者在类的构造函数中初始化:
public YourClassName() // 替换成你的类名
{
    keyCoords = new Dictionary<char, Tuple<int, int>>();
}

2. 完善配置读取逻辑(可选)

为避免配置格式错误引发额外异常,建议增加合法性校验:

// 读取单条配置行示例
string configLine = "c|1807|833";
string[] splitParts = configLine.Split('|');

// 校验分割后的数据长度是否符合要求
if (splitParts.Length == 3)
{
    // 提取字符键
    char key = splitParts[0][0];
    int x, y;
    // 校验坐标是否为有效整数
    if (int.TryParse(splitParts[1], out x) && int.TryParse(splitParts[2], out y))
    {
        keyCoords[key] = Tuple.Create(x, y);
    }
    else
    {
        // 处理坐标格式错误的情况
        Console.WriteLine($"配置行 {configLine} 坐标格式无效");
    }
}
else
{
    // 处理配置行格式错误的情况
    Console.WriteLine($"配置行 {configLine} 格式不正确");
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 22:55:16