C# 如何使用{get;set;}从form1到form2获取变量?
全部 我是C#的新手。我知道这是一个非常流行的问题。但我不明白。我知道有个错误,但在哪里? 例如,Form1代码的第一部分包括私有变量测试,我需要在Form2中获取该变量的值。错误在哪里C# 如何使用{get;set;}从form1到form2获取变量?,c#,winforms,C#,Winforms,全部 我是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;
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;
}
}
}
您没有在方法中的任何位置使用字符串测试。试试这个:
private void button1_Click(object sender, EventArgs e)
{
Form2 dlg = new Form2();
dlg.Test = "test this point";
dlg.Show();
}
查看如何将值分配给Form2对象dlg
上的属性Test
注意:我对属性
测试使用了capital,因为这是关于属性名称样式的普遍共识。在您的表单2中,您使用的是公共属性,因为它是公共的
,您可以通过表单1中的对象分配它。例如:
private void button1_Click(object sender, EventArgs e)
{
Form2 dlg = new Form2();
dlg.test = "test this point";
dlg.Show();
}
有几种方法可以在表单2中使用它,如果您只想让它设置标签的文本属性,那么这将是最好的:
public partial class Form2 : Form
{
public string test
{
get { return label1.Text; }
set { label1.Text = value ;}
}
public Form2()
{
InitializeComponent();
}
}
在属性的setter中,如果需要,您也可以调用函数。test是一个可用于Form2
(最好是测试)的属性,而字符串测试的范围仅限于Form1
的单击事件。除非您将其转让,否则它与财产无关
Form2 dlg = new Form2();
dlg.test = test; // this will assign it
dlg.Show();
现在Form2
属性已获得值,该值将用于在标签中显示相同的值您是对的,这类问题已被问过多次,版本略有不同。。。以下是我过去提供的一些答案
您必须将其分配给Form2 test
属性。您拥有的是一个独立字符串,它和Form2
的属性无关<代码>dlg.test=测试需要Form1
中的code>。谢谢。但是如何在Form2中使用这个变量呢?好的。但是如何在Form2中使用这个变量。我改变了密码,但什么都没发生?!