简体   繁体   English

如何在 C# 中使用参数调用 Main 中的方法?

[英]How can I call a method in Main with a paramter in C#?

I have 'StudentNum' declared as an int in my StudentNumber method in the parameter list, but the program keeps telling me it does not exist in the current context.我在参数列表的 StudentNumber 方法中将 'StudentNum' 声明为 int,但程序一直告诉我它在当前上下文中不存在。 Does anybody know why?有人知道为什么吗? Sorry I am very new to C# and in a past C++ class when we called functions I remember jus doing something like: StudentNumber(StudentNum).对不起,我对 C# 很陌生,在过去的 C++ 类中,当我们调用函数时,我记得我只是在做这样的事情:StudentNumber(StudentNum)。 When I remove StudentNum from the parameter list, the program then says "No overload for method 'StudentNumber' takes 0 arguments. I want the program to prompt the user for a number, and if it is less than 20 then they get the message saying so. Thanks! Here's my code:当我从参数列表中删除 StudentNum 时,程序然后说“方法 'StudentNumber' 没有重载需要 0 个参数。我希望程序提示用户输入一个数字,如果它小于 20,那么他们会收到消息说所以。谢谢!这是我的代码:

namespace RegisterStudent
{
  public class Program
  {
    static void Main(string[] args)
    {
      Console.WriteLine("Hi. Please Enter The Student Number Then Press Enter");
      Console.ReadLine();
      StudentNumber();
    }

    public static void StudentNumber(int StudentNum)
    {

      if (StudentNum > 20)
      {
        Console.WriteLine("Sorry, the class is full.");
        Console.ReadLine();
      }
      else
      {
        Console.WriteLine("You are now enrolled in the course");
        Console.ReadLine();
      }

    }

    public static void StudentHours()
    {

    }
    public static void Conflict()
    {

    }
  }
}

Change your lines改变你的线条

Console.ReadLine();
StudentNumber();

as作为

StudentNumber(int.Parse(Console.ReadLine()));

your problem that you arent passing any argument to your function StudentNumber(int StudentNum) the error tell you that there is no any overloaded function that has no argument so you should pass int paramater to StudentNumber() to work correctly您没有将任何参数传递给函数StudentNumber(int StudentNum)的问题,错误告诉您没有任何没有参数的重载函数,因此您应该将int参数传递给StudentNumber()才能正常工作

Console.ReadLine(); read string line so it should be converted to int by one of these methods:读取字符串行,因此应通过以下方法之一将其转换为int

Int.Parse()

Convert.ToInt()

Int.TryParse()

here the correct version of the code :这里是代码的正确版本:

static void Main(string[] args)
    {
      int stdnum;
      Console.WriteLine("Hi. Please Enter The Student Number Then Press Enter");
      stdnum=Convert.ToInt32(Console.ReadLine());
      StudentNumber(stdnum);
    }

or instead you can use :或者你可以使用:

stdnum=Int32.Parse(Console.ReadLine());

I think that clarify your problem now.我认为现在可以澄清您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM