为项目设置 属性 的值会导致 NullReferenceException

Seting value of a property for an item causes NullReferenceException

基本上我想做的是在客户列表中添加一个客户,在客户列表中有一个 属性 BillToContact。我想为客户创建一个 BillToContact 实例。

public class Customer 
{
    public string  ID { get; set; }
    public string  AccountName { get; set; }
    public Contact BillToContact { get; set; }
}

public class BillToContact
{
    public string firstname { get; set; }
    public string LastName  { get; set; }
}

public class Contact
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

// 下面是尝试将 BillToContact 添加到 Customer

public void test()
{
  List<Customer> Customer = new List<Customer>();

  Customer x = new Customer();
  x.ID   = "MyId";
  x.AccountName = "HelloAccount";
  x.BillToContact.FirstName = "Jim";
  x.BillToContact.LastName  = "Bob";

  Customer.Add(x);
}

这次尝试的错误是

Object reference not set to an instance of an object.

我也曾尝试在 Customer 中创建 BillToContact 的实例,但没有成功。为了避免混淆,问题是我试图在客户列表中创建一个 BillToContact 实例。

您必须实例化 属性 成员才能设置其属性:

Customer x = new Customer();
x.ID   = "MyId";
x.AccountName = "HelloAccount";
x.BillToContact = new BillToContact();
x.BillToContact.FirstName = "Jim";
x.BillToContact.LastName  = "Bob";

仅实例化父级 class 不会自动实例化任何 组合 classes(除非您在构造函数中这样做)。

您需要实例化 BillToContact

所以要么:

x.BillToContact = new BillToContact {FirstName = "Jim", LastName="Bob"};

 x.BillToContact = new BillToContact();
 x.BillToContact.FirstName = "Jim";
 x.BillToContact.LastName = "Bob";

两者等价

其他两个答案都是正确的,因为对象需要实例化,但我发现您的代码有一个问题。没有必要创建一个名为 BillToContact 的单独 class,因为它与 Contact class 具有完全相同的属性。如果您需要 BillToContact 除了 Contact class 中已有的属性之外还有更多属性,您可以通过使 BillToContact 成为 class 的子 class 来执行继承Contact.

此外,您甚至可以从 Customer 的默认构造函数中进行构造函数调用,这样您就可以在知道对象不会为 null 的情况下立即按照我下面的示例分配值:

public class Customer 
{
    public string  ID { get; set; }
    public string  AccountName { get; set; }
    public Contact BillToContact { get; set; }

    //Contructor
    public Customer()
    {
        //Instantiate BillToContact 
        BillToContact = new Contact();
    }
}

Customer x = new Customer();
x.ID = "MyId";
x.AccountName = "HelloAccount";

//This would now work because BillToContact has been instantiated from within the constructor of the Customer class
x.BillToContact.FirstName = "Jim";
x.BillToContact.LastName  = "Bob";

Customer.Add(x);

或者,您也可以为 Contact class 创建一个构造函数,并让它接受名字和姓氏作为参数。这样您就可以创建一个新的 Contact 对象并一次填充名字和姓氏,见下文:

public class Contact
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public Contact() {}

    public Contact(string firstName, string lastName)
    {
        this.FirstName = firstName;
        this.LastName = lastName;
    }
}

Customer x = new Customer();
x.ID = "MyId";
x.AccountName = "HelloAccount";
x.BillToContact = new Contact("Jim", "Bob");
Customer.Add(x);