c# - 如何循环 Console.ReadLine?

标签 c#

我不知道如何在循环中读取用户输入(使用 Console.ReadLine)。我正在尝试创建一个注释,让我可以存储用户输入的内容,并在他键入 exit 时退出。

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {

            Note myNote = new Note();
            Note otherNote = new Note();
            myNote.addText("Hi there");
            Console.WriteLine(myNote.display());
            otherNote.addText(Console.ReadLine());
            Console.WriteLine(otherNote.display());
            if (otherNote = "exit")
            {

            }

        }
    }


}


    class Note
{
    private string text = "";
    private DateTime timeStamp = DateTime.Now;
    private DateTime modifiedStamp = DateTime.Now;
    int maxLength = 10;


    public void addText(string sometext)
    {
        if (text.Length + sometext.Length < maxLength)
        {
            text += sometext;
            modifiedStamp = DateTime.Now;
        }

    }

    public string display()
    {
        return "Created: " + timeStamp.ToString() + "\n" +
            "Modified: " + modifiedStamp.ToString() + "\n" +
            "Content: " + text;
    }
}

最佳答案

您需要笔记列表才能添加任意数量的笔记。 此外,您需要先保存 ReadLine 输入检查用户是否真的要求退出,否则继续添加注释。

var myNotes = new List<Note>();
var firstNote = new Note();
firstNote.addText("Hi there");

Note note;
while (true)
{
    var input = Console.ReadLine();
    if (input.Equals("exit", StringComparison.OrdinalIgnoreCase))
    {
        break;
    }
    note = new Note();
    note.addText(input);
    myNotes.Add(note);
}

关于c# - 如何循环 Console.ReadLine?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32363719/

相关文章:

c# - 使用 asp.net 设置标题标签

c# - Shopify api 更新变体返回错误

c# - 到处获取所有按下的键

c# - 如何在 Entity Framework 中检索一段时间(-10 个月)的数据?

c# - TextBoxFor decimal

c# - 设置控件的属性时,ASP.NET 引号字符编码会导致问题

c# - 在我的 C# 应用程序中。我正在将远程机器的 CNC 程序读入字节缓冲区。如何将这个字节缓冲区逐行读取到字符串数组中?

C# UI 事件取消订阅 - 必要吗?

c# - b/w public variable 和 public auto 属性有什么区别

c# - Tesseract OCR 引擎无法从自动生成的图像中读取文本,但可以从 MS Paint 中的 CUT 读取文本