在set属性中使用console.ReadLine()

Paw*_*wel 2 c# console properties console.readline

我是一个初学者,目前正在学习c#,我想知道是否可以在属性的set部分内使用Console.ReadLine(),然后像使用方法一样使用它来读取用户输入,如下所示:

class Employee
{
    protected int empID;
    public int EmployeeID
    {
        set
        {
            Console.WriteLine("Please enter Employee ID:");
            this.empID = int.Parse(Console.ReadLine());
        }
    }
    //more code here
}
class Program
{
    static void Main(string[] args)
    {
        Employee employee1 = new Employee();
        employee1.EmployeeID;
        //more code here
    }
}
Run Code Online (Sandbox Code Playgroud)

或唯一的选择是直接在“ Main”中使用Console.ReadLine(),如下所示:

class Employee
{
    protected int empID;
    public int EmployeeID { set; }
    //more code here
}
class Program
{
    static void Main(string[] args)
    {
        Employee employee1 = new Employee();
        employee1.EmployeeID = int.Parse(Console.ReadLine());
        //more code here
    }
}
Run Code Online (Sandbox Code Playgroud)

预先感谢您提供所有答案!


谢谢大家的答案!现在,我可以看到这是编写代码的错误方法,而且我理解为什么。我以为通过使用'Console.ReadLine();' 在'set'属性中,将更容易从用户那里获取值,并且我不必重写这一部分:'

Console.WriteLine("Please enter Employee ID:");
this.empID = int.Parse(Console.ReadLine());
Run Code Online (Sandbox Code Playgroud)

每次我都会要求用户输入。但是我现在明白为什么不应该使用它。
再次感谢您提供所有答案,祝您有美好的一天!

Jon*_*zzi 5

是的,您可以放入Console.ReadLine()一个套装。但这是非常错误的。

C#属性的编译方法与方法类似,因此您可以将任何可用的C#代码放入属性中,编译器将允许您执行此操作。(您的代码中的问题是您没有为该集合编写正确的调用)。

但是考虑良好实践和SOLID,这是非常错误的。您的第二个代码段看起来要好得多。

编辑:关于您的代码,

如果您完全按照编写的方式运行代码,我会注意到您的消息"Please enter Employee ID:"永远不会显示。发生这种情况是因为对财产的getset方面存在误解。

查看以下特定行:

employee1.EmployeeID;
Run Code Online (Sandbox Code Playgroud)

这行代码是get对property 的调用EmployeeID。也许这并不明显,因为您没有使用获得的价值。但是这行类似于:

var notUsedVar = employee1.EmployeeID;
Run Code Online (Sandbox Code Playgroud)

要使用set属性操作,您需要使用归因操作,例如:

employee1.EmployeeID = 0; // or
employee1.EmployeeID++; // or
employee1.EmployeeID--; // or
employee1.EmployeeID += 1; // and so on...
Run Code Online (Sandbox Code Playgroud)

片段ps:第一行是您对某个set操作的一次调用,但下面的行既有get调用,又有set调用。

这里有一些代码片段可以确认并理解我的意思:

class Employee
{
    private int _employeeID;

    public int EmployeeId
    {
        get
        {
            Console.WriteLine("The Employee.EmployeeId get operation was called.");
            return _employeeID;
        }
        set
        {
            Console.WriteLine("The Employee.EmployeeId set operation was called.");
            _employeeID = value;
        }
    }
}

class Program
{
    public static void Main()
    {
        var e = new Employee();

        e.EmployeeId++; // or any other exaple.
    }
}
Run Code Online (Sandbox Code Playgroud)

如果运行此代码,您将获得输出:

调用Employee.EmployeeId get操作。
调用Employee.EmployeeId设置操作。

  • 这个答案是非常错误的,最好应该是一个注释。如果您提到的是“非常错误”,则发布一些支持注释的代码,以显示OP应该如何使用getter和setter将值分配给属性。 。 (2认同)