[英]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.