如何使用用户输入使方法参数可选?(C#) [英] How do I make a method parameter optional with user input? (C#)

查看:30
本文介绍了如何使用用户输入使方法参数可选?(C#)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 C# 中有一个名为operator"的对象,它的方法从用户那里获取两个数字输入并将它们相加.但是,我想将第二个参数(第二个输入)设为可选,以便在用户不输入第二个数字时默认为4".

I have an object called "operator" in C# with a method that takes two number inputs from a user and adds them together. However, I want to make the second parameter (2nd input) optional so that the default is "4" if the user doesn't enter a second number.

我知道出了什么问题,因为如果用户只输入一个数字并在提示第二次输入时按回车键,它只会结束程序而不是使用默认值.

I know something's wrong because it just ends the program rather than using the default if the user enters just one number and hits enter when prompted for second input.

这个解决方案可能非常明显,但我无法理解.如果有人能查看我的代码并了解我遗漏了什么,我将不胜感激.

This solution is probably very obvious but it's eluding me. I'd appreciate if someone would take a look at my code and see what I'm missing.

非常感谢!

程序代码:

class Program
{
    static void Main(string[] args)
    {
        Operator operatorObject = new Operator();
        Console.WriteLine("Pick a number:");
        int userValue = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Pick another number--optional");
        int userValue2 = Convert.ToInt32(Console.ReadLine());

        int result = operatorObject.operate(userValue, userValue2);

        Console.WriteLine(result);
        Console.ReadLine();
    }
}

课程代码:

public class Operator
{
    public int operate(int data, int input=4)
    {
        return data + input;
    }           
}

更新:感谢大家的回答!由于各种建议,我想我现在已经开始工作了.非常感谢您的帮助!

UPDATE: Thank everyone for your answers! I think I've got it working now, due to a combination of suggestions. Your help is much appreciated!

推荐答案

如果您省略输入值,则输入 Console.ReadLine 将返回空字符串,该字符串肯定无法转换为整数.

If you omit to enter a value the input Console.ReadLine will return the empty string which surely can´t be converted to an integer.

因此,为了能够省略参数,您需要指出如果用户输入了任何内容:

So in order to enable the parameter to be omitted you need to indicate if the user entered anything at all:

int userValue2, userValue2;
int result;
Console.WriteLine("Pick a number:");
if(!int.TryParse(Console.ReadLine(), out userValue))
    throw new ArgumentException("no valid number");

Console.WriteLine("Pick another number--optional");
if(int.TryParse(Console.ReadLine(), out userValue2)
    result = operatorObject.operate(userValue, userValue2);
else
    result = operator.operate(userValue);

int.TryParse 尝试解析用户提供的输入,如果解析失败将返回false.因此,如果用户键入完全不同的内容,例如 "MyString",这也适用.

int.TryParse tries to parse the input provided by user and if parsing fails will return false. So this also works if user types something completely different like "MyString".

这篇关于如何使用用户输入使方法参数可选?(C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆