“未将对象引用设置到对象的实例” 是 C# 中常见的 编译错误,通常发生在你试图访问一个 未初始化的变量 或 未赋值的引用类型 时。
❗ 问题原因
这个错误通常出现在以下情况:
1. 你试图访问一个 未初始化的变量(即 null)
string myVar;
Console.WriteLine(myVar); // 错误:未将对象引用设置到对象的实例
2. 你试图访问一个 未初始化的引用类型(如 List<T>、Dictionary<T>、object 等)
List<string> myList;
myList.Add("Hello"); // 正确
Console.WriteLine(myList[0]); // 正确
但如果你这样写:
List<string> myList;
myList.Add("Hello"); // 正确
Console.WriteLine(myList); // 正确
那么 myList 是 null,此时 myList 是 null,你直接访问它就会出错。
✅ 解决方法
方法 1:初始化变量
string myVar = "Hello"; // 正确
Console.WriteLine(myVar);
方法 2:使用 null 检查
string myVar = null;
if (myVar != null)
{
Console.WriteLine(myVar);
}
方法 3:使用 as 操作符(当需要安全访问时)
string myVar = null;
string result = myVar as string; // 返回 null,而不是抛出异常
Console.WriteLine(result);
方法 4:使用 null 与 ?. 语法(C# 8+)
string myVar = null;
string result = myVar?.ToString(); // 返回 null,而不是抛出异常
Console.WriteLine(result);