2016-09-22 40 views
0
using System; 
using System.Collections.Generic; 
using System.Collections.ObjectModel; 

namespace ConsoleApplication11 
{ 

    class Customer 
    { 

     public List<string> Strings 
     { 
      get; 

     } = new List<string>(); 
     class Program 
     { 
      static void Main(string[] args) 
      { 
       Customer myCustomer = new Customer(); 
       myCustomer.Strings.Add("test"); 
      } 
     } 
    } 
} 

最後,可以在屬性聲明中添加Strings集合而不用set。爲什麼c#設計就像那樣?如果collection的工作方式與其他普通屬性一樣,會更容易理解,對嗎?爲什麼集合屬性可以在沒有設置的情況下進行更改?

回答

4

它運行正常,您沒有設置該操作的屬性。 List<>是一個對象,您所做的只是調用已分配給Strings屬性的對象的方法。

如果你要做到這一點,而不是:

static void Main(string[] args) 
{ 
    Customer myCustomer = new Customer(); 
    myCustomer.Strings = new List<string>(); 
} 

你會發現,它不能編譯,因爲它試圖爲新值分配給不具有制定者的屬性。

-1

看這行代碼:

public List<string> Strings { get; } = new List<string>(); 

它可能看起來像這樣的代碼是說,財產Strings持有字符串列表。但事實並非如此,因爲在C#中,變量不能包含對象。此代碼表示屬性Strings引用保存爲字符串列表。

將元素添加到此列表中時,不會更改Strings屬性的值。您正在修改該對象,但您並未修改該引用。既然你不改變Strings屬性的值,你不需要一個setter。

+0

我發現這個答案是有點脫節,因此它是混亂。 – Enigmativity

+0

@Enigmativity這很公平。感謝您的反饋意見。 –

相關問題