我正在尝试创建2个表单。
在表单1中我想保存所有新联系人,所以我可以稍后显示它们,我正在添加第二个按钮打开表单2,我想要创建联系人,关闭窗口后将联系人保存到列表中在表单1中创建。我收到错误:
Can not reference a type through an expression
f2.Contacts = this.contacts;
,我不知道原因。
表格1:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Contacts contacts = new Contacts();
public Form1()
{
InitializeComponent();
}
public class Contacts
{
private List<Contacts> people = new List<Contacts>();
public List<Contacts> People
{
get { return people; }
}
}
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.Contacts = this.contacts;
f2.Show();
}
}
}
表格2:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form2 : Form
{
public class Contacts
{
private List<Person> persons = new List<Person>();
public List<Person> Persons
{
get
{
return this.persons;
}
}
}
public Contacts contacts { get; set; }
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Person p = new Person();
p.Name = textBox1.Text;
p.LastName = textBox2.Text;
p.PhoneNumber = textBox3.Text;
p.eMail = textBox4.Text;
this.contacts.Persons.Add(p);
}
public class Person
{
public string Name { get; set; }
public string LastName { get; set; }
public string PhoneNumber { get; set; }
public string eMail { get; set; }
}
}
}
答案 0 :(得分:3)
您(意外地)引用了嵌套的Contacts
类。当你使用
f2.Contacts = this.contacts;
您指的是类 Form2.Contacts
。
但您想引用Form2.contacts
属性:
f2.contacts = this.contacts;