“没有给出与所需形式参数对应的参数”的问题

本文关键字:参数 问题 | 更新日期: 2023-09-27 18:14:11

这是我的代码

static void Main(string[] args)
    {
       Program.AgeAndLabel();
    }
public static string AgeAndLabel(string userAge)
    {
        Console.WriteLine("Enter your age.");
        int ageValue = int.Parse(Console.ReadLine());
        if (ageValue < 18)
            userAge = "Minor";
        else
            userAge = "Adult";
        return userAge;
    }

程序。AgeAndLabel,我得到错误"没有给出对应于'Program.AgeAndLabel(string)'所需的形式参数' userage '的参数",我不明白为什么。我是这个网站的新手,所以如果你有任何建设性的批评,请告诉我。

“没有给出与所需形式参数对应的参数”的问题

string userAge从函数参数中删除,并将其添加到函数中;这就是需要它的地方。问题是变量不存在于你赋值给它的函数作用域中。

而且,你调用的函数没有参数,这意味着你的意思是函数没有参数。

你的函数应该看起来像这样:

public static string AgeAndLabel()
{
    string userAge;
    Console.WriteLine("Enter your age.");
    int ageValue = int.Parse(Console.ReadLine());
    if (ageValue < 18)
        userAge = "Minor";
    else
        userAge = "Adult";    
    return userAge;
}

如果使用了三元操作符,最后五行可以简化为:

return (ageValue < 18) ? "Minor" : "Adult";

,但它只是表达同一事物的另一种(更短的)方式。(虽然更少的代码(通常)意味着更少的错误风险)