使用控制台.集合属性内的ReadLine()
本文关键字:ReadLine 属性 控制台 集合 | 更新日期: 2023-09-27 18:10:21
我是一名初级程序员,目前正在学习c#,我想知道是否可以在属性的集合部分使用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
}
}
或者唯一的选择是直接在"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
}
}
提前感谢您的回答!
谢谢大家的回答!我现在明白了这是一种错误的代码编写方式,我明白了原因。我认为使用"Console.ReadLine((;"在"set"属性中,从用户那里获得值会更容易,我不必重写这一部分:">
Console.WriteLine("Please enter Employee ID:");
this.empID = int.Parse(Console.ReadLine());
每次我都会要求用户输入。但我现在明白了为什么不应该使用它
再次感谢您的回答,祝您今天愉快!
是的,您可以将Console.ReadLine()
放入集合中。但这是非常错误的。
C#属性的编译类似于方法,所以您可以将任何可用的C#代码放入属性中,编译器将允许您这样做。(代码中的问题是您没有正确地编写对集合的调用(。
但从良好实践和S.O.L.I.D的角度来看,这是非常错误的。您的第二个代码片段看起来好多了。
编辑:关于您的代码,
如果您完全按照所写的方式运行代码,我会注意到您的消息"Please enter Employee ID:"
从未显示。发生这种情况是因为对属性的get
和set
方面存在误解。
看看这条特定的线:
employee1.EmployeeID;
这行代码是对属性EmployeeID
的get
调用。也许这并不明显,因为您没有使用goted值。但这条线类似于:
var notUsedVar = employee1.EmployeeID;
要使用属性的set
操作,您需要一个属性操作,如:
employee1.EmployeeID = 0; // or
employee1.EmployeeID++; // or
employee1.EmployeeID--; // or
employee1.EmployeeID += 1; // and so on...
代码段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.
}
}
如果你运行这个代码,你会得到输出:
已调用Employee.EmployeeId获取操作
已调用Employee.EmployeeId集合操作。
public class Employee
{
public int EmployeeID { get; set; }
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please enter Employee ID:");
var empID = int.Parse(Console.ReadLine());
var employee1 = new Employee
{
EmployeeID = empID
};
}
}
Getters
和Setters
应仅用于设置/返回Property持有的任何值。您还可以创建私有字段,并使用不同的方法设置这些字段。但是,您不会从类中调用Console.ReadLine()
。类是实体的表示形式。
您正朝着错误的方向前进。正确的方法是通过Main
方法。
或者,无论出于什么原因,如果你想把功能放在你的类中,它应该是这样的
class Employee
{
protected int empID;
public int EmployeeID
{
get { return empId; }
}
//more code here
public void AskEmployeeID()
{
Console.WriteLine("Please enter Employee ID:");
this.empID = int.Parse(Console.ReadLine());
}
}
现在您可以将Employee
对象上的此函数调用为employee1.AskEmployeeID();