对象映射时出现NullReferenceException

时间:2013-01-14 09:10:19

标签: c# object mapping nullreferenceexception xserver

我试图映射一个对象(它之前已经有效了!)但是,在这个新的应用程序中,它似乎抛出了我似乎无法理解的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;
    }

2 个答案:

答案 0 :(得分:1)

假设point.kmlpoint.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
        };
    }

答案 1 :(得分:1)

您的代码没有任何空引用检查,可能是本身为null,或者 point.kml 为null,或者甚至是其他地方,您应该尝试调试,在visual studio中转动中断异常函数时(CTRL + ALT + E,这里是VS2005的文档参考:Exceptions Dialog Box)来查找哪一行确切地说,它很容易抛出异常然后修复它。