-2

我正在 cosmos ( C# ) 中创建一个操作系统,但我无法正确编写代码。这里是:

var input = Console.ReadLine();
if (input = 'h')
    Console.Write("This is the help section...");
else
    Console.Write("Invalid Command.");
Console.WriteLine(input);

我想要它做的是,当我输入“H”时,它应该输出帮助部分,当我输入其他内容时,它应该输入“无效命令”。

它一直说'错误:无法将类型'char'隐式转换为'string'。

完整代码

using System;
using System.Collections.Generic;
using System.Text;
using Sys = Cosmos.System;

namespace Dingo_OS
{
    public class Kernel : Sys.Kernel
    {
        protected override void BeforeRun()
        {
        Console.WriteLine("Thank you for trying out my OS. For any help, input /h.");
        }

        protected override void Run()
        {
            var input = Console.ReadLine();
            if (input = 'h')
                Console.Write("This is the help section...");
            else
                Console.Write("Invalid Command.");
            Console.WriteLine(input);
        }
    }
}
4

2 回答 2

1

Console.ReadLine返回一个字符串,而不是单个字符。因此,您需要将其与字符串进行比较。字符串文字使用双引号,而不是单引号。此外,您需要相等比较运算符 ( ==) 而不是赋值运算符 ( =):

if (input == "h")

老实说,如果你对 C# 的经验不够丰富以至于这会给你带来问题,我建议你先退后一步,在更“正常”的环境(例如控制台或客户端应用程序)中学习 C# 的基础知识,然后再冒险进入宇宙。我自己没有做过任何 Cosmos 工作,但我怀疑会有一些非常棘手的领域,如果首先没有扎实的 C# 基础,这将变得更加困难。

于 2013-09-08T06:52:10.787 回答
0

Console.ReadLine返回 a stringnot a char,可Console.ReadKey().KeyChar用于阅读char

protected override void Run()
{
    var input = Console.ReadKey().KeyChar;
    if (input == 'h')
        Console.Write("This is the help section...");
    else
        Console.Write("Invalid Command.");
    Console.WriteLine(input);
}
于 2013-09-08T06:56:03.460 回答