2017-03-05 58 views
0

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

上找到.NET Tutorials

**型「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; } 
     } 

    } 
    } 

回答

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"; 
} 
0
Jhon.shippingadress = new Address(); 
相關問題