无法通过表达式引用类型的原因

本文关键字:引用类型 表达式 | 更新日期: 2023-09-27 18:26:50

我正在尝试创建两个表单。

在表格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; }
        }
    }
}

无法通过表达式引用类型的原因

您(意外)引用了嵌套的Contacts类。当你使用

f2.Contacts = this.contacts;

您引用Form2.Contacts

但是您想要引用Form2.contacts属性:

f2.contacts = this.contacts;