c# - 如何避免 'Object reference not set to an instance of an object' ?

标签 c# visual-studio

我一直在一遍又一遍地遇到同样的问题,而我刚才又做了一次。我写了一行代码:

int LAID = db.GetLAByLatLong(address.Latitude, address.Longitude);

...并且 Visual Studio 报告该行没有任何问题。

但是当我运行代码时它报告:

Object reference not set to an instance of an object

我做错了什么?为什么 Visual Studio 似乎说代码没问题,但在运行时却报错?我似乎经常这样做,我真的很想了解我做错了什么,这样我就可以避免它。

最佳答案

您的代码中有两个对象:

db

address

您在所示代码中引用了两个对象。至少其中一个为空。

为避免该问题,请确保在代码运行之前已初始化这两个对象。您还可以添加检查,例如

if (db == null) throw new Exception("The variable db is null.");

关于c# - 如何避免 'Object reference not set to an instance of an object' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15536223/

相关文章:

c# - 在 C# 中将资源 (XML) 添加到 DLL

c# - 将文件复制到目录(c : or c:program files) that i dont have permission

amazon-web-services - 无法在 Amazon (aws) 上创建/删除/发布 Lambda,收到 403 拒绝访问

visual-studio - 在visual studio中显示文件夹

c# - Access sql 以使用自动编号创建表

c# - .NET/C# 的拼写检查器

c# - 安全软件许可证使用审计日志

c# - 单击一次不将 appsettings 安装到用户计算机

asp.net-mvc - 无法在 vs 2015 中的特定项目上启动 IIS Express Web 服务器

c# - 我怎样才能弄清楚刚刚运行的代码是什么?