简体   繁体   English

如何在 C# 中的多个上下文中使用 class 的单个实例?

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

I'm trying to write a console RPG game in C#.我正在尝试在 C# 中编写控制台 RPG 游戏。 I have a Party class containing a list of Heroes, PlayerTeam .我有一个包含英雄列表 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 am thrown an error stating The name 'PlayerTeam' does not exist in the current context. Any help is appreciated. 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.感谢任何帮助。

Welcome!欢迎! Since a Main method is always static, any non-local variables referenced in the Main method must also be static.由于Main方法始终是 static,因此Main方法中引用的任何非局部变量也必须是 static。 Mark your PlayerTeam variable as static.将您的PlayerTeam变量标记为 static。

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

Longer term, you will want to create some sort of Game object and have it create all of your state, rather than having static variables all over the place.从长远来看,你会想要创建某种游戏 object 并让它创建你所有的 state,而不是到处都有 static 变量。

You need to move the declaration of PlayerTeam from inside your Main() method out to CLASS level so that it is accessible from anywhere:您需要将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