如何在类的“设置”函数中捕获空异常?(C#)

我应该编写一个程序,让用户输入一本书的名称、描述和页数,如果名称或描述为空,或者页数小于零,程序应该捕获异常. 老师说我们需要在类的“set”函数中捕捉异常,但我似乎无法正确理解。这是类的样子:


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 方法,我会很高兴听到)。我的问题是,即使名称和描述字符串明显有输入,仍然会抛出空异常。有人知道我该如何解决吗?任何帮助,将不胜感激。


侃侃尔雅
浏览 176回答 2
2回答

catspeake

在SetDescription并且SetName您正在检查字段/成员变量而不是 if 语句中的参数。改为检查参数(this在 if 条件下为否)。

MMMHUHU

你有名字冲突。您实际上是在检查私有字段,而不是传递给您的方法的参数。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值)。
打开App,查看更多内容
随时随地看视频慕课网APP