我们是否只是因为希望能够调用方法而将某些东西放在括号内?

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

当我调用

Check
方法时,我将“5”放在括号中。我这样做是因为它需要一个整数来调用该方法。这与用户输入有什么关系,还是能够调用方法是必要的?

我怎么能不把一些东西放在括号里,但仍然可以调用

Check
方法?

static void Main(string[] args)
{
    Check(5);
    Console.Read();
}

public static void Check(int myInt)
{
    Console.WriteLine("Enter a number to checkc if it is odd or even number: ");
    string userInput = Console.ReadLine();
    int userInputNum;
    int parsedValue;

    if (Int32.TryParse(userInput, out userInputNum))
    {
        parsedValue = userInputNum;
    }
    else
    {
        parsedValue = 0;
        Console.WriteLine("You did not enter a number or anything.");
    }

    if ((parsedValue % 2) == 0)
    {
        Console.WriteLine("It is a even number.");
    }
    else
    {
        Console.WriteLine("It is an odd number.");
    }
}
c# methods user-input
2个回答
1
投票

public static void Check(int myInt)
方法的声明声明它接受一个强制性的
int
参数并调用它
myInt
.

正因为如此,无论在哪里调用

Check
方法,都必须为这个参数提供一个值:
Check(5)
Check(100)
Check(Random.Shared.NextInt())
等等

调用没有参数值的方法是非法的,即

Check()
.

现在,方法

Check
接受一个强制参数
int myInt
,但它实际上并没有在任何地方使用它。既然参数没用,不妨把它从方法要求中去掉。

public static void Check()
{
...

从方法签名中删除

int myInt
参数后,调用该方法时不再需要为该参数提供值。您只需在代码中使用
Check()
即可调用无参数方法。


-2
投票

你可以像这样让

myInt
可以为空:
public static void Check(int? myInt = null)
或者你可以让
myInt
有一个默认值:
public static void Check(int myInt = 5)

您可以在here

阅读有关可空值类型的信息
© www.soinside.com 2019 - 2024. All rights reserved.