c# - 尝试编写像 Unity 这样的最小行为系统时,循环似乎会阻塞

标签 c#

我尝试编写一个 API,允许以 Unity 的方式创建行为。这只是学习这种语言的一个小实验,我对编程总体来说也是新手。

我制作的测试类应该无限期地将您在构造函数中指定的内容写入控制台,但没有输出。循环似乎被阻塞了。 这是我写的:

1 - 程序.cs

using System.IO;

namespace Program {
    
    public abstract class Script {
        public abstract void Start();
        public abstract void Update();
    }
    
    class Program {
        
        static bool IsKeyDown(ConsoleKey key) {
            if (Console.ReadKey(true).Key == key) return true;
            else return false;
        }
        
        public static void Main(string[] args) {
            Script[] scriptList = {
                new Write("Hello World"),
            };
            foreach (Script s in scriptList) {
                s.Start();
            }
            while (!IsKeyDown(ConsoleKey.Escape)) {
                foreach (Script s in scriptList) {
                    s.Update();
                }
            }
        }
    }
}

2 - Write.cs

using System;

namespace Program {

    public class Write : Script {
        string str;
        public Write(string _str) {
            str = _str;
        }
        public override void Start(){}
        public override void Update(){
            Console.WriteLine(str);
        }
    }
}

最佳答案

您的代码块位于Console.ReadKey上。如果输入缓冲区中没有可用的按键,则 ReadKey 将停止并等待用户按下按键。
您可以在他们所说的文档中阅读此信息

One of the most common uses of the ReadKey() method is to halt program execution until the user presses a key and the app either terminates or displays an additional window of information.

您只需添加

static bool IsKeyDown(ConsoleKey key)
{
    if (!Console.KeyAvailable) return false;
    if (Console.ReadKey(true).Key == key) return true;
    else return false;
}

关于c# - 尝试编写像 Unity 这样的最小行为系统时,循环似乎会阻塞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59590332/

相关文章:

c# - 将 DataGridView 单元格值转换为 DateTime

c# - 使用 C# 的 Microsoft.Office.Interop.Excel 生成具有预填充下拉值的 Excel 文件

c# - VLC:将文件移动到末尾

c# - 在 Web 应用程序内部调试控制台应用程序

c# - 使用 C++ 中的 COM 对象,在 C#.NET 中返回对象 []

c# - 如何使用紧凑的框架创建多行 RadioButton

c# - 在 Visual Studio 中编译时获取程序集名称

c# - 使用 Blazor 中的选择框筛选数据列表

c# - 这是一个错误吗?具有私有(private)访问修饰符构造函数的 Activator.CreateInstance?

c# - Linq 查询按活跃月份汇总