gpt4 book ai didi

c# - 在这种情况下我应该使用异常(exception)吗?

转载 作者:行者123 更新时间:2023-11-30 19:22:03 26 4
gpt4 key购买 nike

我设计了一个简单的程序,它有一个计数器类,在那个计数器类中,我有增加计数、减少计数等的方法。然后我向用户显示一个菜单并让他们输入他们的选择,例如。为选项一输入 1,等等。好吧,我不希望计数为负数,因此为了处理这个问题,我让计数器类的 SubtractCount 方法在计数 < 0 时抛出 ArguemetOutOfRangeException。

然后我让我的 switch 语句捕获发生的异常。我的问题是:使用异常来确保计数永远不会为负是否不好?我应该做不同的事吗?或者更好的是,是否有更好的方法来实现这一目标?

代码片段:

static void Driver()
{
switch (userChoice)
{
case 1: // if user picks a 1, the count is deincremented
try {

myObjectOfCounterClass.SubtractCount();
}
catch (ArguemetOutOfRangeException ex)
{
console.writeLine(ex.message);
}
break;
// case 2, case 3 etc.
}

class Counter
{
private int count;

public void SubtractCount()
{
if (count < 0)
throw new ArguementOutOfRangeException("The count can never be negative!");
else
count--;
}

最佳答案

将异常用于控制流不被认为是好的做法。在你的例子中,Tester-Doer模式会更合适。

您可以将您的 Counter 类更改为如下所示:

class Counter
{
private int count;

public bool CanSubtractCount
{
get { return this.count >= 0; }
}

public void SubtractCount()
{
if (!this.CanSubtractCount)
throw new InvalidOperationException("The count can never be negative!");
else
this.count--;
}

您现在可以像这样重写您的客户端:

static void Driver()
{
switch (userChoice)
{
case 1: // if user picks a 1, the count is deincremented
if(myObjectOfCounterClass.CanSubtractCount)
{
myObjectOfCounterClass.SubtractCount();
}
else
{
// Write a message to the user?
}
break;
// case 2, case 3 etc.
}
}

关于c# - 在这种情况下我应该使用异常(exception)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1802228/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com