gpt4 book ai didi

c# - 使用属性在表单之间传输数据

转载 作者:太空宇宙 更新时间:2023-11-03 20:00:02 26 4
gpt4 key购买 nike

我正在尝试使用属性将两个集合从一种形式转移到另一种形式。但是由于某种原因,我在 form1 中看不到 form2 的属性。我收到的错误信息是

System.Windows.Forms.Form does not contain a defintion for _col1 and no extension method _col1 accepting a first argument of type System.windows.Forms.Form....

这是Form1的代码

 public partial class Form1 : Form
{

private Collection<string> col1;
private Collection<string> col2;

private void btn1_Click(object sender, EventArgs e)
{
Form frm1 = new Form2();

//fill collections with some kind of data

frm1._col1 = _col1;
frm1._col2 = _col2;

frm1.Show();
}
public Collection<string> _col2
{
get { return col2; }
}

public Collection<string> _col1
{
get { return col1; }
}
}

这是Form2的代码

public partial class Form2 : Form
{
private Collection<string> col1;
private Collection<string> col2;

public Form2()
{
InitializeComponent();
}

public Collection<string> _col1
{
get { return col1; }

set { col1 = value; }
}

public Collection<string> _col2
{
get { return col2; }

set { col2 = value; }
}
}

根据我读过的文章,一切都应该有效 - 但是我无法从 Form1 访问 Form2 属性。

我错过了什么??

最佳答案

您已经声明了您的 frm1像这样的变量:

Form frm1 = new Form2();

因此,编译器会假设它是 Form 类型.正如错误消息正确解释的那样,Form没有任何名为 _col1 的属性或方法.

如果您将变量声明为属于 Form2 类型相反,编译器会找到您的属性:

Form2 frm1 = new Form2();

正如 CoderDennis 评论的那样, 你也可以使用 var keyword而不是显式声明变量的类型:

var frm1 = new Form2();

但是请注意,C# programming guide注意事项:

However, the use of var does have at least the potential to make your code more difficult to understand for other developers. For that reason, the C# documentation generally uses var only when it is required.

一般来说,这不是一个不明智的代码,只要 var不会替换一些非常难写的东西(例如泛型类型)。


关于编码风格的评论:约定属性以大写字母开头,因此您可能希望将属性从 _col1 重命名。和 _col2Col1Col2 ,分别。

如果您随后想在视觉上清楚地区分私有(private)字段的属性,请在私有(private)字段的名称中加上下划线,正如 CoderDennis 所正确指出的那样在他的评论中。

关于c# - 使用属性在表单之间传输数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29469853/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com