我一直在一遍又一遍地遇到同样的问题,而我刚才又做了一次。我写了一行代码:
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/