2013-12-18 22 views
-1

在下面的代碼中,即使集合聲明爲readonly,我們也能夠將項目添加到集合中。但它是一個已知的事實,如readonly修飾符將允許在聲明,初始化表達式或構造函數中初始化該值。 以下可能如何? readonly修改器如何在不同類型上運行?帶只讀修飾符的集合如何在C#中變得可修改?

class Program 
{ 
    static void Main(string[] args) 
    { 
     ReadonlyStringHolder stringHolder = new ReadonlyStringHolder(); 
     stringHolder.Item = "Say Hello";//compile time error-Read only field cannot be initialized to 

     ReadOnlyCollectionHolder collectionHolder = new ReadOnlyCollectionHolder(); 
     collectionHolder.ItemList.Add("A"); 
     collectionHolder.ItemList.Add("B");//No Error -How Is possible for modifying readonly collection 

     Console.ReadKey(); 
    } 
} 

public class ReadOnlyCollectionHolder 
{ 
    public readonly IList<String> ItemList = new List<String>(); 
} 
public class ReadonlyStringHolder 
{ 
    public readonly String Item = "Hello"; 
} 
+1

'IList'本身不能設置。但沒有任何東西阻止你調用它的方法。 –

+0

相關:http://stackoverflow.com/questions/55984/what-is-the-difference-between-const-and-readonly – Anthony

+2

'只讀'很淺 - 它適用於該字段,而不是字段所指的任何內容至。 –

回答

2

改爲使用ReadOnlyCollection

readonly不允許只是更改實例(除了構造函數)

public class ReadOnlyCollectionHolder 
{ 
    private List<string> _innerCollection=new List<string>(); 

    public ReadOnlyCollectionHolder() 
    { 
     ItemList = new ReadOnlyCollection<String> (_innerCollection); 
    } 

    public readonly ReadOnlyCollection<String> ItemList {get;private set;} 
} 
+1

基本上,'readonly'改變了變量本身的可變性(限制它只是構造函數可以設置的值)而不是後備對象的可變性。 – Anthony

+0

是的,這是正確的 – Artiom

+0

@Anthony我明白了..謝謝 – amesh

1

你不能改變ITEMLIST實例,但你可以調用它的方法。 如果你真的想要一個只讀列表,你應該考慮使用IReadOnlyList<T>ReadOnlyCollection<T>