无法通过表达式引用类型为什么?
问题描述:
我正在尝试创建2个表单。无法通过表达式引用类型为什么?
在表单1中,我想保存所有新联系人,以便以后可以显示它们,并且我添加第二个按钮,打开表单2,在其中创建联系人并关闭窗口后将联系人保存到已创建表格1.我得到错误列表:
Can not reference a type through an expression
上,我不知道为什么。
形式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; }
}
}
}
答
您是(偶然)指的是嵌套Contacts
类。当您使用
f2.Contacts = this.contacts;
您参考类Form2.Contacts
。
但要参考Form2.contacts
财产:
f2.contacts = this.contacts;
来吧伙计。 “联系人”是类名称,“联系人”是您想要分配给的内容。不知道为什么你有'联系人'实施两次,但这是另一个问题。 – helrich 2014-10-17 11:47:55
纯语法错误。 'f2.Contacts'中的'Contacts'是一个类型,而不是属性。 – 2014-10-17 11:48:19
f2,'Contacts'是一个类,你的属性被称为'contacts' – 2014-10-17 11:48:39