奇怪的IndexOutOfRangeException,即使被抓住了

时间:2011-05-24 07:10:32

标签: c# visual-studio-2010 xna xna-4.0

好吧,我有一个公共静态const:

public static ChatLine[] chatLine = new ChatLine[numChatLines];

调试显示了这段代码(稍后在同一个文件中):

for (int num12 = 0; num12 < numChatLines; num12++)
{
    chatLine[num12] = new ChatLine();
}

将鼠标移到每个数据点上时,它会显示num12为0且chatLine为chatLine [0]。这是非常奇怪的,因为我的公共const就像我在上面给你看的那样......知道为什么会这样吗?

完整堆栈跟踪如下:

System.IndexOutOfRangeException was unhandled
  Message=Index was outside the bounds of the array.
  Source=Project1
  StackTrace:
       at Project1.Main.Initialize() in C:\Users\X\My Documents\Project1\Main.cs:line 7590
       at Microsoft.Xna.Framework.Game.RunGame(Boolean useBlockingRun)
       at Microsoft.Xna.Framework.Game.Run()
       at Project1.Program.Main(String[] args) in C:\Users\X\My Documents\Project1\Program.cs:line 14
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.Runtime.Hosting.ManifestRunner.Run(Boolean checkAptModel)
       at System.Runtime.Hosting.ManifestRunner.ExecuteAsAssembly()
       at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext, String[] activationCustomData)
       at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext)
       at System.Activator.CreateInstance(ActivationContext activationContext)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 

2 个答案:

答案 0 :(得分:6)

chatLine的长度为零时,创建数组时numChatLines为零。您应该在设置numChatLines

后创建数组

答案 1 :(得分:0)

这可能是因为 numChatLines

之后被赋予了一个值
public static ChatLine[] chatLine = new ChatLine[numChatLines];

..已初始化,这将提供 0 值。

尝试:

public static ChatLine[] chatLine;
void main()
{
  /* ... your code ... */
  numChatLines = 12;
  chatLine = new ChatLine[numChatLines];
}