C# - Must be misunderstanding something about static
got this little line of code. when I run it, I get "Object reference not set to an instance of an object" on the line "Roads_Vertices[i, 0] = Convert.ToDouble(Coordinates[0]);". Help !
Thanks Gabriel
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.GetEle开发者_如何学编程mentsByTagName("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
}
}
}
}
You did not initialize the static array:
Roads_Vertices = new double[Road_Vertices_NodeList.Count,2];
Static means it can be accessed without an instance of the type it is enclosed by, or by static methods inside it, but not that it does not have to be initialized.
Trying to say it in english:
There will be a Road_Vertices that will be static and a double multidimensional array:
static double[,] Roads_Vertices; // declaration
And here it is, as big as it matters:
Roads_Vertices = new double[Road_Vertices_NodeList.Count,2]; // definition
you need to initialize Road_Vertices
and Road_Segment
. you have only declared them, you have not assigned a value to the variables.
you need to do something like:
static double[,] Roads_Vertices=new double[someValue,someOtherValue];
精彩评论