Winforms中的C#和变量作用域 [英] C# and Variable Scope in Winforms

查看:60
本文介绍了Winforms中的C#和变量作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Winform应用程序中,我希望实例化类中的数据可以通过多个表单控件访问。

Within a Winform app, I would like data in an instantiated class to be accessible by multiple form controls.

例如,如果我创建Class Foo,它具有一个名为name的字符串属性,我想通过单击Button1实例化Foo a = new a(),当我单击Button2时,我希望能够使用MessageBox.Show(a.name)。如果真的很重要,可能会有多个Foo实例。

For example, if I create Class Foo, which has a string property of name, I'd like to instantiate Foo a = new a() by clicking Button1, and when I click Button2, I'd like to be able to MessageBox.Show(a.name). There may be multiple instances of Foo, if that matters at all.

以这种方式使用类实例的最佳选择是什么?

What is my best option for being able to use class instances in such a way?

推荐答案

一个类的私有字段或属性满足要求-此类的所有方法都可以访问该字段。

A private field or property of a class satisfies the requirement - such field can be accessed by all methods of the class.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Test
{
    public partial class Form1 : Form
    {
        foo a;
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            a = new foo();
            a.name = "bar";
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (a != null && a.name != null)
                MessageBox.Show(a.name);
            else 
                MessageBox.Show("");
        }
    }

    public class foo
    {
        public string name { get; set; }

        public foo() { }
    }
}

如果您希望此变量可被其他形式访问,则需要将其公开(最好是作为属性)-

If you want this variable to be accessible to other forms you'd need to make it public (preferably as property) - C# winform: Accessing public properties from other forms & difference between static and public properties

这篇关于Winforms中的C#和变量作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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