You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现类似Unity的可点击C#控制台输出行?

常规C#开发中实现控制台输出跳转至源码行(Rider适用)

当然可以实现,核心是让控制台输出符合IDE解析规则的「文件路径+行号」格式——这不是什么特殊超链接,主流IDE(包括Rider)都内置了对这类格式的识别,会自动把路径行号部分变成可点击的跳转入口。

具体实现方法

1. 手动获取并输出源码位置

通过System.Diagnostics.StackTrace可以拿到当前代码的文件路径和行号,按格式输出后,Rider就能识别并支持跳转:

// 获取当前代码的调用栈帧
var stackTrace = new System.Diagnostics.StackTrace(true);
var callerFrame = stackTrace.GetFrame(0); // 0代表当前执行的这一行
if (callerFrame != null)
{
    var fileName = callerFrame.GetFileName();
    var lineNum = callerFrame.GetFileLineNumber();
    // 按Rider识别的格式输出
    Console.WriteLine($"{fileName}:{lineNum}: 这是测试输出");
}

运行后,控制台里的文件名:行号部分会变成蓝色可点击链接,点击直接跳转到对应源码行。

2. 封装成通用工具方法

像Unity的Debug.Log那样封装一个静态方法,方便全局调用:

public static class ConsoleDebug
{
    public static void Log(string message)
    {
        var stackTrace = new System.Diagnostics.StackTrace(true);
        // 取索引1的帧,因为索引0是Log方法本身,1才是调用Log的那一行代码
        var callerFrame = stackTrace.GetFrame(1);
        if (callerFrame == null)
        {
            Console.WriteLine(message);
            return;
        }
        
        var fileName = callerFrame.GetFileName();
        var lineNum = callerFrame.GetFileLineNumber();
        // 格式化输出,兼容Rider/VS等IDE
        Console.WriteLine($"[{fileName}:{lineNum}] {message}");
    }
}

使用时直接调用ConsoleDebug.Log("测试内容");,输出的结果就能直接跳转。

关键注意事项

  • 必须开启调试信息生成:Debug模式默认开启,Release模式如果需要这个功能,要在项目属性→生成→高级→调试信息中选择「完整」或「pdb-only」,否则StackTrace无法获取文件名和行号。
  • 不同IDE的识别格式略有差异,但文件名:行号是通用基础格式,Rider、Visual Studio都能识别。

内容的提问来源于stack exchange,提问作者Adam B

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 21:15:33