gpt4 book ai didi

c# - 重构以删除 try/catch

转载 作者:太空狗 更新时间:2023-10-29 23:55:47 25 4
gpt4 key购买 nike

有什么好的方法可以重构它,使我的代码行为相同,但不需要抛出和捕获我自己的异常吗?

public Int32 ChooseNextColor(Int32 numColors)
{
int? nextColor = null;

while (nextColor == null)
{
Console.Write("Please enter your next color selection: ");
string input = Console.ReadLine();

try
{
nextColor = Convert.ToInt32(input);
if (nextColor > numColors || nextColor < 0)
throw new ArgumentOutOfRangeException();
}
catch
{
nextColor = null;
Console.WriteLine("Unrecognized input: " + input);
Console.WriteLine("Please enter a value between 0 and " + numColors + ".");
}
}

return (nextColor.Value);
}

编辑:try/parse 方法正是我要找的。

作为对 John 标题编辑的回应 -> 我本应该发布更多信息作为开始,那就是“一起摆脱 try/catch 是最好的”。因此,考虑到这一点,我更改了标题。

最佳答案

尝试

int nextColor;
input = Console.ReadLine();

while( ! Int32.TryParse( input, out nextColor )
|| nextColor > numColors
|| nextColor < 0 )
{
Console.WriteLine("Unrecognized input: " + input);
Console.WriteLine("Please enter a value between 0 and " + numColors + ".");
input = Console.ReadLine();
}

关于c# - 重构以删除 try/catch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2045353/

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