请问一个很弱的问题:如何在构造函数中初始化成员
syhan 2006-01-01 06:04:08 比如说:
class Graph
{
private string[] NodeList;
private int[,] Edge;
public Graph(int sz)
{
string[] NodeList = new string[sz];
for (int j = 0; j < sz; j++)
{
NodeList[j] = "";
}
int[,] Edge = new int[sz, sz];
for (int i = 0; i < sz; i++)
{
for (int j = 0; j < sz; j++)
{
Edge[i, j] = 0;
}
}
}
}
}
编译之后也能通过,但是有如下两个警告:
Warning 1 Field 'Traffic.Graph.NodeList' is never assigned to, and will always have its default value null E:\Visual Studio 2005\Projects\Traffic(DS)\Traffic\Graph.cs 10 26 Traffic
Warning 2 Field 'Traffic.Graph.Edge' is never assigned to, and will always have its default value null E:\Visual Studio 2005\Projects\Traffic(DS)\Traffic\Graph.cs 11 24 Traffic
然后我运行时程序就抛出异常了System.NullReferenceException was unhandled
Message="Object reference not set to an instance of an object."
Source="Traffic"
StackTrace:
at Traffic.Graph.InsertNode(String name) in E:\Visual Studio 2005\Projects\Traffic(DS)\Traffic\Graph.cs:line 98
at Traffic.Form1.button2_Click(Object sender, EventArgs e) in E:\Visual Studio 2005\Projects\Traffic(DS)\Traffic\Form1.cs:line 65
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.Run(Form mainForm)
at Traffic.Program.Main() in E:\Visual Studio 2005\Projects\Traffic(DS)\Traffic\Program.cs:line 19
at System.AppDomain.nExecuteAssembly(Assembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
我是green hand ,大家多帮忙啊,谢谢了