小编Paw*_*wel的帖子

当用户输入null或空字符串时抛出错误

我正在尝试解决以下练习:

您需要创建一个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)

.net c# string exception-handling

9
推荐指数
2
解决办法
8794
查看次数

在set属性中使用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 …
Run Code Online (Sandbox Code Playgroud)

c# console properties console.readline

2
推荐指数
1
解决办法
1774
查看次数