C# - 必须误解一些关于静态的东西

时间:2011-04-30 13:42:24

标签: c# static

获得了这一小段代码。 当我运行它时,我在“Roads_Vertices [i,0] = Convert.ToDouble(Coordinates [0]);”这一行上得到“对象引用未设置为对象的实例”。 帮助!

由于 加布里埃尔

namespace RouteSim
{
static class Program
{
    static double[,] Roads_Vertices;
    static double[,] Roads_Segments;

    static void Main()
    {
        // Declarations and Initializations
        // Read Roads from XML
        Parse_Road_Data();

        // User Interface
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form_MainWindow());
    }

    static void Parse_Road_Data()
    {
        // Reads and parses the Roads XML file
        XmlDocument Road_File = new XmlDocument();
        Road_File.Load(@"D:\My Documents\Visual Studio 2010\Projects\RouteSim\Additional Data\Roads.xml");

        XmlNodeList Road_Vertices_NodeList = Road_File.GetElementsByTagName("Road_Vertex");
        for (int i = 0; i < Road_Vertices_NodeList.Count; i++)
        {
            string[] Coordinates = Road_Vertices_NodeList[i].InnerText.Split(new Char[] { ' ' });
            Roads_Vertices[i, 0] = Convert.ToDouble(Coordinates[0]);
            Roads_Vertices[i, 1] = Convert.ToDouble(Coordinates[1]);
        }

        XmlNodeList Road_Segments_NodeList = Road_File.GetElementsByTagName("Road_Segment");
        for (int i = 0; i < Road_Segments_NodeList.Count; i++)
        {
            string[] Coordinates = Road_Segments_NodeList[i].InnerText.Split(new Char[] { ' ' });
            Roads_Segments[i, 0] = Convert.ToDouble(Coordinates[0]);
            Roads_Segments[i, 1] = Convert.ToDouble(Coordinates[1]);
            // Readall the rest of the data
        }
    }
}
}

2 个答案:

答案 0 :(得分:5)

您没有初始化静态数组:

Roads_Vertices = new double[Road_Vertices_NodeList.Count,2];

静态意味着可以在没有它所包含的类型的实例的情况下访问它,或者通过其中的静态方法访问它,但不是它不必初始化。

试着用英语说:

将会有一个静态的Road_Vertices和一个双多维数组:

static double[,] Roads_Vertices; // declaration

在这里,重要的是:

 Roads_Vertices = new double[Road_Vertices_NodeList.Count,2]; // definition

答案 1 :(得分:0)

您需要初始化Road_VerticesRoad_Segment。你只声明了它们,你还没有为变量赋值。

你需要做类似的事情:

static double[,] Roads_Vertices=new double[someValue,someOtherValue];
相关问题