c#的所有函数和方法都会抛出异常

本文关键字:方法 抛出异常 函数 | 更新日期: 2023-09-27 18:07:17

无论函数/方法是什么,它总是会导致游戏崩溃。我有两个项目,一个用于UI,一个用于引擎。UI包含一个Forms应用程序。引擎包含一个World.cs静态类。如果我试图从World中引用一个函数/方法(但不是变量),它将抛出异常。我甚至写了一个函数:

public static void Potato()
{
    int pot;
    pot = 0;
}

在World.cs中,并在corei .cs(表单应用程序)中引用它:

World.Potato();

抛出了一个异常。它只抛出一个World类的异常。我还有另外两个公共静态类,可以引用它们而不会引发异常。有人能解释一下发生了什么吗?如果我需要提供更多的代码,我会的。谢谢!

World.cs:

using System;
using System.Collections.Generic;
using System.Text;
namespace Engine
{
    public static class World
    {
    public static readonly int[] world;
    public const int worldSize = 20;
    private static Random rand = new Random();
    //Constructor
    static World()
    {
        GenerateWorld();
    }
    private static void GenerateWorld()
    {
        for (int i = 1; i < worldSize-2; i += 1)
        {
            world[i] = ChooseLandType(rand.NextDouble());
        }
        world[0] = 0;
        world[19] = 4;
    }
    private static int ChooseLandType(double a)
    {
        if (a <= 0.5d) return 0;
        else if (a > 0.5d && a <= 0.55d) return 1;
        else if (a > 0.55d && a <= 0.8d) return 2;
        else if (a > 0.8d && a <= 0.9d) return 3;
        else if (a > 0.9d) return 4;
        else return 0;
    }
    public static int GetLocationType(int a)
    {
        if (a < worldSize) return world[a];
        else return 0;
    }
}
}

CoreUI.cs中的相关代码:

private void btnForward_Click(object sender, EventArgs e)
    {
        _player.MoveTo(_player.Y + 1);
        float a = (100f * (_player.Y / 20f));
        a = Clampf(a,0,100);
        pbPos.Value = (int)a;
        //The next line is the Thrown Exception
        pBoxIMG.Image = GetImage(World.GetLocationType(_player.Y));
    }

异常详情复制到剪贴板:

System.TypeInitializationException was unhandled
  HResult=-2146233036
  Message=The type initializer for 'Engine.World' threw an exception.
  Source=Engine
  TypeName=Engine.World
  StackTrace:
       at Engine.World.GetLocationType(Int32 a)
       at SomeProgram.CoreUI.btnForward_Click(Object sender, EventArgs e) in C:'Users'user'Documents'Visual Studio 2010'Projects'SomeProgram'SomeProgram'CoreUI.cs:line 43
       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(IntPtr 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 SomeProgram.Program.Main() in C:'Users'user'Documents'Visual Studio 2010'Projects'SomeProgram'SomeProgram'Program.cs:line 18
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly 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.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: System.NullReferenceException
       HResult=-2147467261
       Message=Object reference not set to an instance of an object.
       Source=Engine
       StackTrace:
            at Engine.World.GenerateWorld() in C:'Users'user'Documents'Visual Studio 2010'Projects'SomeProgram'Engine'World.cs:line 23
            at Engine.World..cctor() in C:'Users'user'Documents'Visual Studio 2010'Projects'SomeProgram'Engine'World.cs:line 17
       InnerException: 
简化:

Engine的类型初始化项。

c#的所有函数和方法都会抛出异常

您没有初始化world

所以你需要加上

static World()
{
    world = new int[worldSize];
    GenerateWorld();
}

您所展示的初始方法没有任何问题,所以问题出在代码的另一部分。

在您所展示的类中,有一个静态构造函数:
class World
{
    // ...
    static World()
    {
        GenerateWorld();
    }
    // ...
}

静态构造函数(和静态初始化器)可以延迟执行——也就是说,在您第一次使用特定类时执行。如果它们运行良好,那么就没有问题,你甚至不会注意到它们。

但是如果它们碰巧因为任何原因抛出异常,(在调试期间)就会显得好像是你的方法抛出了异常。但实际上你的初始方法是无辜的——它只是导致CLR在加载特定类时运行真正的罪魁祸首方法。

换句话说,异常是从GenerateWorld()方法抛出的。正如其他人所说,这是因为您正在索引数组:

world[i] = // ...

但是你没有先初始化数组:

world = new int[worldSize];