簡體   English   中英

如何在 C# 中使用參數調用 Main 中的方法?

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

我在參數列表的 StudentNumber 方法中將 'StudentNum' 聲明為 int,但程序一直告訴我它在當前上下文中不存在。 有人知道為什么嗎? 對不起,我對 C# 很陌生,在過去的 C++ 類中,當我們調用函數時,我記得我只是在做這樣的事情:StudentNumber(StudentNum)。 當我從參數列表中刪除 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()
    {

    }
  }
}

改變你的線條

Console.ReadLine();
StudentNumber();

作為

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

您沒有將任何參數傳遞給函數StudentNumber(int StudentNum)的問題,錯誤告訴您沒有任何沒有參數的重載函數,因此您應該將int參數傳遞給StudentNumber()才能正常工作

Console.ReadLine(); 讀取字符串行,因此應通過以下方法之一將其轉換為int

Int.Parse()

Convert.ToInt()

Int.TryParse()

這里是代碼的正確版本:

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);
    }

或者你可以使用:

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

我認為現在可以澄清您的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM