[英]Call Main from another method
有沒有辦法從另一種方法“手動”調用Main()
? 我有以下代碼:
static void Main(string[] args) {
# some code
function();
}
static void function() {
#some code
Main(); # Start again
}
我有簡單的控制台計算器,當我在function()
計算和打印結果時,我想在Main()
方法中再次使用例如“輸入兩個數字:”。
您還必須添加參數。 如果您不在主要功能中使用該參數,您必須具備以下可能性:
null
作為參數 null作為參數
這將是這樣的:
static void code()
{
Main(null);
}
可選屬性
然后你必須像這樣修改參數:
static void Main (string[] args = null)
//...
你不能刪除Main函數中的參數,因為它被其他一些東西調用,你不想修改。
如果你在main函數中使用args參數,null可能不是一個好主意,那么你應該用new string[0]
類的東西替換它:
static void code()
{
Main(new string[0]);
}
但是,這作為可選參數無效,因為可選參數必須是編譯時常量 。
如果您將它與null
一起使用,則可以在不使用之前檢查null
值的情況下使用它時獲取NullReference異常 。 這可以通過兩種方式完成:
if條件看起來像這樣:
static void Main (string[] args = null)
{
Console.Write("Do something with the arguments. The first item is: ");
if(args != null)
{
Console.WriteLine(args.FirstOrDefault());
}
else
{
Console.WriteLine("unknown");
}
code();
}
像這樣的空傳播 :
static void Main(string[] args = null)
{
Console.WriteLine("Do something with the arguments. The first item is: " + (args?.FirstOrDefault() ?? "unknown"));
code();
}
順便說一句,你在Main()
調用后忘記了一個分號。
也許你應該重新考慮你的代碼設計,因為你在main
方法中調用code
方法和code
方法中的main
方法,這可能導致無限循環,因此在StackOverflow異常中 。 您可以考慮將code
方法中要執行的code
放在另一個方法中,然后在main
方法內部和code
方法內部調用:
static void Initialize()
{
//Do the stuff you want to have in both main and code
}
static void Main (string[] args)
{
Initialize();
code();
}
static void code()
{
if (condition /*you said there'd be some if statement*/)
Initialize();
}
在這里您可以獲得有關方法的更多信息。 但是,因為這是通常occurrs在學習如何代碼開頭的問題,你應該經歷這樣一個教程這樣 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.