为Console.Readlines输入创建对象是否正确?

时间:2018-03-23 18:41:15

标签: c# object console

我刚刚开始学习C#,所有这些类,对象和方法仍然让我困惑。所以我提出了这段代码,它的工作正常,但我觉得我做的事情是我不应该做的。有些C#专家可以看一下吗?

这是获取输入然后使用它的好方法吗?

static void Main(string[] args)
{
    input crInput = new input();
    Console.WriteLine(crInput.evalInput(Console.ReadLine()));
}

private class input
{
    public string InputString { get; set; }

    public string evalInput(string _input)
    {
        string result = "";

        string input = _input;

        if (input == "1")
        {
            result = "1";
        }
        else if (input == "2")
        {
            result = "2";
        }
        else if (input == "3")
        {
            result = "3";
        }
        else
        {
            result = "NOTHING";
        }

        return result;
    }
}

1 个答案:

答案 0 :(得分:1)

正如我在您的代码中看到的,可以修复几个细节: 首先,您可以通过在C#中替换关键字var:var CRInput = new Input();的类名来简化CRInput赋值。 var 支持几乎所有类型的数据。

要考虑的另一件事是类的名称应该以Capital开头,这是正确的方法。

另一件事是,如果您之前已有一个string input,则无需创建另一个static void Main(string[] args) { //var supports almost all types of data, which simplifies the object declaration process var CRInput = new Input(); Console.WriteLine(CRInput.EvalInput(Console.ReadLine())); } //Class names must start with capitals private class Input { public string InputString { get; set; } public string EvalInput(string input) { //Initialize result with the value -> "" string result = string.Empty; //The switch structure simplifies and shortens the repetitive use of else if switch (input) { //if case "1": result = "1"; break; //else if case "2": result = "2"; break; //else if case "3": result = "3"; break; //else default: result = "NOTHING"; break; } return result; } }

开关关键字可以简化重复使用其他内容,如果你能看到的话,建议每个句子都有自己的一行。

public class Employee
{
    protected String name;
    protected String employeeNum;
    protected String department;
    protected char type;
    protected BufferedWriter printer;
}  


public void writeData() throws IOException
{
    Scanner sc = new Scanner (System.in);
    System.out.println("Please enter the name of the new file for next week");
    String newFile = sc.nextLine();
    printer = new BufferedWriter(new FileWriter(newFile + ".txt"));
    String data= getData();

    printer.write(data);

}

protected String getData()
{
    return name + " " + employeeNum + " " + department + " " + type;
}

public class Commission extends Employee 
{
    private int weeksStart;
    private double baseWeeklySalary;
    private double salesWeekly;
    private double totalSales;
    private double commissionRate;
}  

@Override
protected String getData()
{
    return name + " " + employeeNum + " " + department + " " + type + " " + weeksStart + " " + baseWeeklySalary + " " + salesWeekly + " " + totalSales + " " + commissionRate;
}