如何在类的“set”函数中捕获null异常? (C#)

问题描述 投票:0回答:2

我应该编写一个程序,让用户输入书籍的名称,描述和页数,如果名称或描述为空,或者页面数低于零,程序应该捕获异常。老师说我们需要在班级的“设定”功能中捕捉异常,但我似乎无法做到正确。这就是这个类的样子:

class Book
{
    private string Name;
    private string Description;
    private int Pages;

    public string GetName()
    {
        return Name;
    }
    public string GetDescription()
    {
        return Description;
    }
    public int GetPages()
    {
        return Pages;
    }

    public void SetName(string Name)
    {
        if (this.Name == null)
            throw new Exception("The name can't be blank");
        else
            this.Name = Name;
    }

    public void SetDescription(string Description)
    {
        if (this.Description == null)
            throw new Exception("The description can't be blank");
        else
            this.Description = Description;
    }

    public void SetPages(int Pages)
    {
       if(Pages > 0)
        {
            this.Pages = Pages;
        }
       else
        {
            Console.WriteLine("Number of pages has to be higher than zero");
        }   
    }
    public void Write()
    {
        Console.WriteLine("Name: {0}, Description: {1}, Pages: {2}", Name, Description, Pages);
    }

}

主要看起来像这样:

Book hp = new Book();
        hp.SetName("Harry Potter");
        hp.SetDescription("It's okay");
        hp.SetPages(-500);
        hp.Write();

我知道SetPages并没有真正使用catch方法,但我认为它仍然有效(尽管如果有人知道如何使用catch方法,我会很高兴听到)。我的问题是,即使名称和描述字符串明显有输入,仍然会抛出null异常。任何人都知道如何解决这个问题?任何帮助,将不胜感激。

c# class exception null throw
2个回答
1
投票

你有一个名字冲突。您实际上是在检查私有字段,而不是传递给方法的参数。

this.Name指的是你班级的私人领域,而不是参数。这就是适当的命名约定很重要的原因。将参数更改为小写以避免混淆,并确保检查null的值:

public void SetName(string name)
{
    if (name == null)
        throw new Exception("The name can't be blank");
    else
        this.Name = name;
}

您可能还想考虑使用静态String函数IsNullOrWhiteSpace

if (String.IsNullOrWhiteSpace(name))
    throw new Exception("The name can't be blank");

私有字段周围也有约定,因此您可能也想更改该字段的名称。例如,命名私有字段的常用方法是:

private string _name;

你的try / catch块总是被触发,因为你总是检查私有字段null。一旦你纠正了字段的问题,将对参数进行检查,字段将被正确设置并且try / catch块不应该执行(当然,除非你传入null值)。


4
投票

SetDescriptionSetName中,您正在检查字段/成员变量而不是if语句中的参数。改为检查参数(if条件下没有this)。

© www.soinside.com 2019 - 2024. All rights reserved.