簡體   English   中英

如何在 C# 中的多個上下文中使用 class 的單個實例?

[英]How do I utilize a single instance of a class over multiple contexts in C#?

我正在嘗試在 C# 中編寫控制台 RPG 游戲。 我有一個包含英雄列表 PlayerTeam 的派對PlayerTeam I instantiate the Party class PlayerTeam in my static void Main(string[] args , and I am trying to write a new function creating an encounter with an enemy. However, when I try to reference the Party class instantiated in the Main function, I我拋出一個錯誤,指出The name 'PlayerTeam' does not exist in the current context.感謝任何幫助。

歡迎! 由於Main方法始終是 static,因此Main方法中引用的任何非局部變量也必須是 static。 將您的PlayerTeam變量標記為 static。

// change this:
// public Party PlayerTream
// to this:
public static Party PlayerTeam;

從長遠來看,你會想要創建某種游戲 object 並讓它創建你所有的 state,而不是到處都有 static 變量。

您需要將PlayerTeam的聲明從Main()方法中移出到 CLASS 級別,以便可以從任何地方訪問它:

public static Party PlayerTeam;

public static void Main(string[] args)
{
    PlayerTeam = new Party();

}

暫無
暫無

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

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