我试图更好地理解课程,课程'地址'用作属性' ShippingAddress'中的类型。在班级' Person',但我想知道如何为地址属性分配值,因为它在下面的方式给我一个错误:
上找到**类型' System.NullReferenceException'的未处理异常发生在Classes_and_Objects.exe
中附加信息:对象引用未设置为对象的实例。**
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Classes_and_Objects
{
class Program
{
static void Main(string[] args)
{
Person john = new Person();
john.FirstName = "John";
john.LastName = "Doe";
john.ShippingAddress.StreetAddress = "78 Fake Street" ;
john.ShippingAddress.City = "Queens";
john.ShippingAddress.State = "NY";
john.ShippingAddress.PostalCode = "345643";
john.ShippingAddress.Country = "United States";
}
}
public class Address
{
public string StreetAddress { get; set; }
public string City { get; set; }
public string State { get; set; }
public string PostalCode { get; set; }
public string Country { get; set; }
}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Address ShippingAddress { get; set; }
}
}
}
答案 0 :(得分:1)
您还需要实例化地址。以下是编写代码的方法:
static void Main(string[] args)
{
Person john = new Person();
john.FirstName = "John";
john.LastName = "Doe";
john.ShippingAddress = new Address();
john.ShippingAddress.StreetAddress = "78 Fake Street" ;
john.ShippingAddress.City = "Queens";
john.ShippingAddress.State = "NY";
john.ShippingAddress.PostalCode = "345643";
john.ShippingAddress.Country = "United States";
}
答案 1 :(得分:0)
Jhon.shippingadress = new Address();