我正在尝试解决以下练习:
您需要创建一个
Product代表产品的类.该类有一个名为的属性Name.Product该类的用户应该能够获取和设置Name属性的值.但是,任何将值设置为Name空字符串或空值的尝试都应引发异常.此外,Product该类的用户不应该能够访问Product该类的任何其他数据成员.你将如何创建这样一个类?
我创建了以下代码但由于某种原因它不会在字符串无效时抛出异常:
class Program
{
static void Main(string[] args)
{
Product newProduct = new Product();
Console.WriteLine("Enter Product name:");
newProduct.Name = null; //Console.ReadLine();
Console.WriteLine("Product name is : {0}", newProduct.Name);
Console.ReadLine();
}
}
class Product
{
private string name;
public string Name
{
get
{
return this.name;
}
set
{
if (Name != String.Empty || Name != null)
{
name = value;
}
else
{
throw new …Run Code Online (Sandbox Code Playgroud) 我是一个初学者,目前正在学习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 …Run Code Online (Sandbox Code Playgroud)