简体   繁体   中英

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#. I have a Party class containing a list of Heroes, 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.

Welcome! Since a Main method is always static, any non-local variables referenced in the Main method must also be static. Mark your PlayerTeam variable as 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.

You need to move the declaration of PlayerTeam from inside your Main() method out to CLASS level so that it is accessible from anywhere:

public static Party PlayerTeam;

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM