C# C如何添加到列表类?

C# C如何添加到列表类?,c#,.net,C#,.net,我试图向list类添加新的obj,但告诉我需要对属性的obj引用。我不能确切地理解我该做什么,你能给我一个提示吗 public class CreateContact { logic... } public class AddedContacts { private List<CreateContact> Contact; public List<CreateContact> ClassCreateContact { get

我试图向list类添加新的obj,但告诉我需要对属性的obj引用。我不能确切地理解我该做什么,你能给我一个提示吗

public class CreateContact
{
  logic...
}

public class AddedContacts
{
    private List<CreateContact> Contact;

    public List<CreateContact> ClassCreateContact
    {
        get { return Contact; }
        set { this.Contact = value; }
    }
}

您已在类中定义了属性,但该属性仅在该类的实例存在时才存在。您需要通过AddedContacts contacts=new AddedContacts创建实例。然后contacts将是对包含列表的实际对象的引用


如果希望类本身包含列表,请将属性声明为static

您需要在AddedContacts类的构造函数中实例化列表:

public class AddedContacts
{
    private List<CreateContact> Contact;

    public List<CreateContact> ClassCreateContact
    {
        get { return Contact; }
        set { this.Contact = value; }
    }

    public AddedContacts()
    {
        Contact = new List<CreateContact>();
        ClassCreateContact = new List<CreateContact>();
    }

}

如果您不使用setter

public class AddedContacts
{
    public readonly List<CreateContact> Contact = new List<CreateContact>();
}

private void button4_Click(object sender, EventArgs e)
{
    CreateContact p = new CreateContact(textBox1.Text, textBox2.Text, textBox3.Text, textBox4.Text);
    AddedContacts ac= new AddedContacts();
    ac.Contact.Add(p);
}

可能是Nope的重复,他试图访问一个静态的实例属性。这两个都是不相关的链接。问题是如何访问实例成员:您需要在AddedContacts类的构造函数中实例化列表!问题的可能重复之处在于,他甚至没有AddedContacts的实例,因此添加字段初始化器不会有任何帮助。你比我的VS副本更快-问题是,他甚至没有AddedContacts的实例,因此添加字段初始化器不会有帮助
 AddedContacts AC = new AddedContacts();
 AC.ClassCreateContact.Add(p);
public class AddedContacts
{
    public readonly List<CreateContact> Contact = new List<CreateContact>();
}

private void button4_Click(object sender, EventArgs e)
{
    CreateContact p = new CreateContact(textBox1.Text, textBox2.Text, textBox3.Text, textBox4.Text);
    AddedContacts ac= new AddedContacts();
    ac.Contact.Add(p);
}