一种压缩多个阅读线的方法? [英] A way to condense multiple readlines?

查看:72
本文介绍了一种压缩多个阅读线的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对编程还很陌生,所以除了到目前为止我们在 C# 类中所做的事情之外,我对自己的了解不多,但我几乎到处都在寻找一种压缩 readlines 的方法,以便程序可以读取许多输入无需为用户输入的每个变量编写读取行代码.

Im pretty new to programming so i dont know much myself other than what we've done in my into c# class so far but i've looked pretty much everywhere for a way to condense readlines so that the program will read many inputs in a row without having to code a readline for every variable the user is inputting for.

        Console.WriteLine("Enter ID for Jane Doe: ");
        c.ID = Console.ReadLine();

        Console.WriteLine("Enter Insurance Name for Jane Doe: ");
        c.Insurance = Console.ReadLine();

        Console.WriteLine("Enter Height(In.) for Jane Doe: ");
        c.Height = Convert.ToInt32(Console.ReadLine());

        Console.WriteLine("Enter Weight(lbs.) for Jane Doe: ");
        c.Weight = Convert.ToSingle(Console.ReadLine());

        Console.WriteLine("Enter Health Status for Jane Doe: ");
        c.HealthStatus = Console.ReadLine();

这个例子来自不久前的一些作业,但让我烦恼的是我找不到压缩代码的方法.基本上我希望能够在一个 writeline 中询问所有信息,然后只使用一种 readline/其他方法输入每个变量,其中用户键入一个变量的信息,点击 Enter,然后重复但经常需要.有没有办法做到这一点,或者我只需要处理重复?

This example is from some homework from a little bit ago but it bothered me that I couldn't find a way to condense the code. Basically I want to be able to ask for all the information in one writeline and then only use one readline/other method for the input of each variable where the user types the info for one variable, hits enter, then repeats however often is needed. Is there any way to do that or do i just have to deal with the repetition?

推荐答案

一般来说,只需要处理重复即可.它清晰、易于调试,而且确实没那么糟糕.

In general, you need to just deal with the repetition. Its clear, easy to debug, and its really not that bad.

现在,您可以这样做:

public class InputRequest
{
     public String Request {get; set;}
     public Action InputMethod {get; set;}
}

然后你会像这样创建:

List<InputRequest> allInputs = new List<InputRequest>();
allInputs.Add(new InputRequest() { Request = "Enter your height", 
    InputMethod = new Action(() => currentPerson.Height = Convert.ToInt32(Console.ReadLine())));

然后你可以遍历它们:

foreach (InputRequest req in allInputs)
{
    Console.WriteLine(req.Request);
    req.InputMethod();
}

但实际上,为了稍微更小的代码,这消除了很多可读性.我可能会在不同上下文中使用这样的模式,但在这里,您的代码很好.

But in all reality, that removes a lot of readability for the sake of slightly smaller code. I would use such a pattern in a different context perhaps, but here, your code is fine.

这篇关于一种压缩多个阅读线的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆