简体   繁体   English

C#从方法访问类实例

[英]C# accessing class instance from method

Seems like I'm struggling with a pretty basic problem right now, but I just can't find a good solution.. 似乎我现在正在为一个非常基本的问题而苦苦挣扎,但我只是找不到一个好的解决方案。

I have this code-snippet here: 我在这里有此代码段:

    public Form1()
    {
        InitializeComponent();

        BaseCharacterClass myChar = new BaseCharacterClass();
    }

    public void setLabels()
    {
        lbName.Text = myChar.CharacterName;
        lbHealthPoints.Text = (myChar.CharHPcurrent + "/" + myChar.CharHPmax);
        lbMagicPoints.Text = (myChar.CharHPcurrent + "/" + myChar.CharMPmax);
        lbClass.Text = myChar.CharacterClass;
    }

It says "myChar" does not exist in the current scope.. 它说“ myChar”在当前范围中不存在。

How do I fix that? 我该如何解决?

You just need to declare myChar outside of the constructor. 您只需要在构造函数之外声明myChar。 You can define it on the class and then assign it on the constructor: 您可以在类上定义它,然后在构造函数上分配它:

BaseCharacterClass myChar;

public Form1()
        {
            InitializeComponent();

            myChar = new BaseCharacterClass();
        }

        public void setLabels()
        {
            lbName.Text = myChar.CharacterName;
            lbHealthPoints.Text = (myChar.CharHPcurrent + "/" + myChar.CharHPmax);
            lbMagicPoints.Text = (myChar.CharHPcurrent + "/" + myChar.CharMPmax);
            lbClass.Text = myChar.CharacterClass;
        }

You didnt declare the variable as a class variable, only a local one. 您没有将变量声明为类变量,而只是局部变量。 In c# the format is: c# ,格式为:

MyNamespace
{
    class MyClassName
    {
        //class wide variables go here
        int myVariable; //class wide variable

        public MyClassName() //this is the constructor
        {
            myVariable = 1; // assigns value to the class wide variable
        }

        private MyMethod()
        {
            int myTempVariable = 4; // method bound variable, only useable inside this method

            myVariable = 3 + myTempVariable; //myVariable is accessible to whole class, so can be manipulated
        }
    }
}

And so on. 等等。 Your current constructor only declares a local variable within the constructor, not a class wide one 您当前的构造函数仅在该构造函数内声明一个局部变量,而不是整个类的局部变量

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

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