繁体   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