【问题标题】:C# accessing class instance from methodC#从方法访问类实例
【发布时间】:2017-05-12 17:01:36
【问题描述】:

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

我这里有这个代码-sn-p:

    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”在当前范围内不存在..

我该如何解决这个问题?

【问题讨论】:

  • 你必须在你的方法之外声明变量。
  • 在此处粘贴代码。在Form1方法的顶部声明变量

标签: c# class methods scope


【解决方案1】:

您只需要在构造函数之外声明 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;
        }

【讨论】:

  • 哇,好的,太好了!
  • 完成。 :) 我可以在其他地方与您联系吗,因为我有另一个问题,其中包含更多代码。
  • 发布到 Stack Overflow。这是我们可以提供帮助的最佳方式。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2015-07-09
    • 1970-01-01
    • 1970-01-01
    • 2021-06-03
    • 2014-01-26
    • 1970-01-01
    • 2011-01-10
    • 2018-11-03
    • 1970-01-01
    相关资源
    最近更新 更多