0
我試圖更好地理解類,類'地址'被用作'Person'類屬性'ShippingAddress'中的類型,但我想知道如何將值分配給地址屬性,因爲它下面的方式是給我一個錯誤:如何將一個類用作另一個類中的屬性,然後實例化它? [C#]
**型「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; }
}
}
}