要在 C# 命令行输出进度,可以使用 Console 类的 Write 和 WriteLine 方法。

以下是一个简单的示例,演示如何在命令行输出进度条:

using System;

class Program
{
    static void Main()
    {
        // 设置进度条长度
        int totalLength = 20;
        
        for (int i = 0; i <= totalLength; i++)
        {
            // 清除当前行的内容
            Console.SetCursorPosition(0, Console.CursorTop);
            Console.Write(new string(' ', Console.WindowWidth));
            
            // 计算进度百分比
            int progress = (int)((float)i / totalLength * 100);
            
            // 输出进度条
            Console.Write('[');
            Console.Write(new string('#', i));
            Console.Write(new string(' ', totalLength - i));
            Console.Write('] {0}%', progress);
            
            // 延迟一段时间
            System.Threading.Thread.Sleep(100);
        }
    }
}

在上面的示例中,我们使用了 Console.SetCursorPosition 方法将光标定位到当前行的开头,然后使用 Console.Write 方法输出进度条的内容。最后,使用 System.Threading.Thread.Sleep 方法延迟一段时间,以模拟进度条的更新。

C# 命令行进度条输出:详细教程及示例

原文地址: https://www.cveoy.top/t/topic/pO0M 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录