如何使用 { get; 从 form1 到 form2 获取变量放;}? [英] How to get variable from form1 to form2 with { get; set;}?

查看:25
本文介绍了如何使用 { get; 从 form1 到 form2 获取变量放;}?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

全部.

我是 C# 的新手.我知道这是一个非常受欢迎的问题.但我不明白.我知道有错误,但在哪里?例如 - 代码 Form1 的第一部分包含私有变量 test,我需要在 Form2 中获取此变量的值.错误在哪里?

I'm newbie in C#. I know this is very popular question. But I didn't understand. I know there is a mistake, but where? For example - first part of code Form1 include private variable test, I need to get the value of this variable in the Form2. Where is the error?

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

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string test = "test this point";
            Form2 dlg = new Form2();
            dlg.test = test;
            dlg.Show();
        }
    }
}

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

namespace WindowsFormsApplication1
{
    public partial class Form2 : Form
    {
        public string test { get; set; }

        public Form2()
        {
            InitializeComponent();
            label1.Text = test;
        }
    }
}

推荐答案

在你的 Form2 中你使用了一个公共属性,因为它是 public 你可以通过 form1 中的对象来分配它.例如:

In your Form2 you are using a public property, because it is public you can assign it via the object in form1. For example:

 private void button1_Click(object sender, EventArgs e)
        {
            Form2 dlg = new Form2();
            dlg.test = "test this point";
            dlg.Show();
        }

在form 2中有几种方法可以使用它,如果您只想设置标签的text属性,这将是最好的:

There are a couple of ways to use this in form 2, if you just want it to set the text property of the label only, this would be the best:

public partial class Form2 : Form
    {
        public string test 
        { 
           get { return label1.Text; }
           set { label1.Text = value ;} 
        }

        public Form2()
        {
            InitializeComponent();
        }
    }

如果需要,您还可以在属性的 setter 中调用函数.

Within the setter of the property you could also call a function if required.

这篇关于如何使用 { get; 从 form1 到 form2 获取变量放;}?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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