winforms按钮方法中的类属性超出范围 [英] Class property out of scope in a winforms button method

查看:93
本文介绍了winforms按钮方法中的类属性超出范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个快速的Windows窗体和类:

I created a quick windows Form and class:

namespace TestClassScope
public partial class Form1 : Form
{
  public Form1()
   {
     InitializeComponent();
     Class1 myClass = new Class1();
   }
  private void button1_Click(object sender, EventArgs e)
  {
     string stuffy = myClass.MyStuff;
  }
}

created a simple class:

namespace TestClassScope
{
    class Class1
    {
        private string myStuff = "Stuff";
        public string MyStuff 
        {
            get { return myStuff; }
            set { myStuff = value; }
        }
    }

The compiler error i get is a sguiggly line under myClass and a tag that states:

"The name 'myClass' does not exist in the current context". When I instantiate the class within the button1_click it's ok. It would be nice to have a class I can instantiate in the public Form1() method and then available throughout all my other form methods. Is this not possible?

I'm a lille jr. to Windows forms. Any ideas on how to deal with this scoping problem?

推荐答案

你应该知道范围规则,表单构造函数中的myClass是作用于该方法的,并且在该构造函数之外不可用,您应该将该变量作为属性放在表单中,以便所有方法都可以访问它。



执行以下操作:



You should be aware of scope rules, the myClass in your form's constructor is scoped to that method and is not available outside that constructor, you should put the variable in the form as a property so all the methods have access to it.

Do the following :

public Form1()
 {
   InitializeComponent();   
 }

Class1 myClass = new Class1(); // a variable for the entire form

这篇关于winforms按钮方法中的类属性超出范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆