如何使用 { get; set;} 获取从 form1 到 form2 的变量

本文关键字:form1 form2 变量 何使用 get set 获取 | 更新日期: 2023-09-27 18:33:32

All.

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

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

如何使用 { get; set;} 获取从 form1 到 form2 的变量

在 Form2 中,您使用的是公共属性,因为它public您可以通过 form1 中的对象分配它。例如:

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

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

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

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

你是对的,这种类型的问题已经被问了很多次了,版本略有不同......以下是我过去提供的一些答案

这可能最接近您正在寻找的内容

一个答案通过方法调用获取值

另一个,逐步创建两个表单,并使用函数或 Getter(setter) 从另一个表单获取值

您没有在方法中的任何位置使用字符串测试。试试这个:

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

了解如何将值分配给 Form2 对象dlg上的属性Test

注意:我对属性Test使用了大写字母,因为这是属性名称样式的普遍共识。

test 是一个可用于Form2的属性(最好是 Test),而 string test 的范围只是 Form1 的 click 事件。它与属性无关,除非您分配它。

Form2 dlg = new Form2();
dlg.test = test; // this will assign it
dlg.Show();

现在Form2属性已经获得了将用于在Label中显示相同值

的值