对象映射时的NullReferenceException
本文关键字:NullReferenceException 映射 对象 | 更新日期: 2023-09-27 17:53:23
我试图映射一个对象(它以前工作过!)然而,在这个新的应用程序中,它似乎抛出了一个我似乎不理解的NullReferenceException
。这里是代码,有人能解决这个问题,并解释这是如何发生的?
private xRoute.Point ConvertXLocate2XRoute(xLocate.Point point)
{
xRoute.Point converted = new xRoute.Point();
//KML
converted.kml.kml = point.kml.kml;
converted.kml.wrappedPlacemarks = point.kml.wrappedPlacemarks;
//POINT
converted.point.x = point.point.x;
converted.point.y = point.point.y;
//WKB
converted.wkb = point.wkb;
//WKT
converted.wkt = point.wkt;
return converted;
}
假设point.kml
和point.point
不为空:
如果xRoute.Point
的构造函数没有实例化它的嵌套对象属性,你必须自己去做:
converted.kml = new ...();
...
converted.point = new ...();
我还建议为这样的映射器编写更简洁的代码:
private xRoute.Point ConvertXLocate2XRoute(xLocate.Point point)
{
return new xRoute.Point
{
kml = new Kml // Replace by the actual name of this type
{
kml = point.kml.kml,
wrappedPlacemarks = point.kml.wrappedPlacemarks
},
point = new Point // Replace by the actual name of this type
{
x = point.point.x,
y = point.point.y,
},
wkb = point.wkb,
wkt = point.wkt
};
}
您的代码没有任何null引用检查,它可能是点本身为null,或者点。kml为null,甚至在其他地方,您应该尝试在visual studio (CTRL+ALT+E,这里是VS2005的文档参考:异常对话框)中打开中断,调试,以便轻松找到哪一行抛出异常,然后修复它。