简体   繁体   English

需要在静态和非静态方法中使用实例

[英]Need to use instance in static and non-static methods

I'm making a little text game. 我正在做一个小文字游戏。 The starting dialogue is in my main (static) method. 开始对话是在我的主要(静态)方法中。 From there, it sends you to other methods depending on your choices. 从那里,它会根据您的选择将您带到其他方法。

Now I think I need to have an instance of my class for this to work. 现在我想我需要一个类的实例才能起作用。

For example: 例如:

Program p = new Program();

if(stuff){
    p.room1();
}
else{
    p.room2();
}

Within those other methods there are global variables that will change. 在其他方法中,全局变量将发生变化。

So above the main method there is: 因此,在主要方法之上有:

public bool hasItem = false;

So room1() would look like, 所以room1()看起来像

public void room1(){
    if(stuff){
        p.hasItem = true;
    } 
}

I know I'm screwing something up with the main method. 我知道我在用主要方法搞砸了。 Do I declare the instance "p" inside or outside of the main method? 我是在main方法内部还是外部声明实例“ p”? I've tried both but get errors both ways. 我都尝试过,但是都遇到错误。

Edit: I ended up declaring a static "Program" outside of the main method to use elsewhere. 编辑:我最终在主要方法之外声明了一个静态“程序”,以在其他地方使用。 Thanks for the help! 谢谢您的帮助!

First off, you can either create a static Program outside of your main method, or declare a program inside your main method, depending on your architecture. 首先,根据您的体系结构,您可以在main方法外部创建一个静态Program ,或者在main方法内部声明一个程序。

Second, you don't have to reference your instance from within your instance methods. 其次,您不必从实例方法中引用实例。 Just use the field name. 只需使用字段名称。 like so: 像这样:

public void room1(){
    if(stuff){
        hasItem = true;
    } 
}

you can use this.hasItem if you want to be explicit about it. 如果您想明确地使用它,可以使用this.hasItem


Or better yet, make a brand new class to keep your state in. Having instance members in the class with the main method is awkward design. 或者更好的方法是,创建一个全新的类来保持您的状态。在类中使用main方法的实例成员是笨拙的设计。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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