首页 > 解决方案 > 仅在单步执行代码时出现 C# 调试错误

问题描述

我的 MonoGame 应用程序在 Visual Studio 中单步执行代码时输出错误,但在运行代码时却没有。我很困惑,想知道我是否违反了一些规则。所以,这里是有问题的代码:

    public class SpacialHash<T>
    {
        public Vector2 Size, CellSize;
        public HashCell<T>[,] Cells;

        public SpacialHash(Vector2 size, Vector2 cellsize)
        {
            Size = size;
            CellSize = cellsize;
            Vector2 hashSize = new Vector2((int)Math.Ceiling(size.X / cellsize.X), (int)Math.Ceiling(size.Y / cellsize.Y));

            Cells = new HashCell<T>[(int)hashSize.X, (int)hashSize.Y];
            for (int x = 0; x < hashSize.X; x++)
            {
                for (int y = 0; y < hashSize.Y; y++)
                {
                    Cells[x, y] = new HashCell<T>(this);
                }
            }
        }

        public HashCell<T> AddMember(Vector2 position, T member)
        {
            Vector2 cpos = new Vector2((int)Math.Floor(position.X / CellSize.X), (int)Math.Floor(position.Y / CellSize.Y));

            //Breakpoint is here
            if (cpos.X < Cells.GetLength(0) && cpos.Y < Cells.GetLength(1) && cpos.X >= 0 && cpos.Y >= 0)
            {
                //The following line of code causes the error while stepping through code
                HashCell<T> cell = Cells[cpos.X, cpos.Y];
                cell.AddMember(member);
                return cell;
            }
            return null;
        }
    }

该函数应该找到成员应该在其中的单元格(通过计算 cpos),这似乎可以正常工作。程序检查 cpos 以确保它在界限内,然后声明单元对象,将其分配给存储在数组中 cpos 的单元的值。执行此操作的代码行会引发以下错误:

System.ExecutionEngineException
  HResult=0x80131506
  Source=<Cannot evaluate the exception source>
  StackTrace:
<Cannot evaluate the exception stack trace>

错误

我什至不知道从哪里开始调试它。奇怪的是,运行代码时不会抛出任何错误,只是在单步执行时。那么,这种行为可能是由简单地使用带有泛型类的多维数组引起的吗?

谢谢,

奥齐

标签: c#visual-studio

解决方案


我猜它绑定了错误版本的 .net 程序集,因为它甚至找不到异常类型(根据您显示的错误消息)。

您可以使用 Fusion Log Viewer (fuslogvw.exe) 更好地确定是否出现故障。Fusion 是 .NET 发布之前的原始代号。

访问该应用程序的最简单方法是启动 Visual Studio 命令提示符(确保以管理员身份运行它 - 否则您将无法进行更改)并键入

fuslogvw <ENTER>

fuslogvw

这是一个非常难看的实用程序,但它可以帮助您确定 .NET 绑定是否失败。

您可以在以下位置查看有关如何设置的更多信息:https ://docs.microsoft.com/en-us/dotnet/framework/tools/fuslogvw-exe-assembly-binding-log-viewer

点击【设置】,进行如下设置:

记录所有绑定到磁盘

现在,只要 .NET 绑定库,它就会将值写入融合日志。返回您的程序并在调试模式下运行它并逐步执行代码,直到它失败。

如果失败,请返回 Fusion Log Viewer 并单击查看日志按钮。
希望您会看到它所绑定的 .NET DLL 的版本。它可能是您为非调试运行所获得的不同版本。

重要的

完成后不要忘记将 Settings 设置回 [Log Disabled],否则所有 .NET 程序都会写入系统范围的日志并降低计算机速度。


推荐阅读