C#从方法访问类实例

时间:2016-12-28 11:53:03

标签: c# class methods scope

现在似乎我正在努力解决一个非常基本的问题,但我找不到一个好的解决方案..

我在这里有这段代码片段:

    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;
    }

它说当前范围内不存在“myChar”..

我该如何解决?

2 个答案:

答案 0 :(得分:3)

你只需要在构造函数之外声明myChar。您可以在类上定义它,然后在构造函数上分配它:

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;
        }

答案 1 :(得分:0)

您没有将变量声明为类变量,只是本地变量。在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
        }
    }
}

等等。您当前的构造函数仅在构造函数中声明局部变量,而不是类宽的