2017-08-31 26 views
-1

我遇到ReadOnlyCollection的覆蓋問題。ReadOnlyCollection的實例

我用兩個集合,一個將與Access數據庫來填充,然後排列和複製的ReadOnlyCollection 與

public static List<ToponymeGeoDb> ListeToponymesGeoDb = new List<ToponymeGeoDb>(); 

public static ReadOnlyCollection<ToponymeGeoDb> roListeToponymesGeoDb = new ReadOnlyCollection<ToponymeGeoDb>(ListeToponymesGeoDb); 

一旦填充我

ToponymeGeoDb.roListeToponymesGeoDb =new ReadOnlyCollection<ToponymeGeoDb>(ToponymeGeoDb.ListeToponymesGeoDb); 
傳輸數據

在這個階段我的roListeToponymesGeoDb包含我的數據,但是當我嘗試在我的程序的另一部分中使用它時,它是空的!

由於它被聲明爲靜態成員,我不明白髮生了什麼。

+0

您不需要「通過數據傳輸」。任何對ListeToponymesGeoDb的更改都會自動反映在ReadOnlyCollection中。請參閱https://msdn.microsoft.com/en-us/library/ms132474(v=vs.110).aspx – WithMetta

+0

如果roListeToponymesGeoDb爲空,則ListeToponymesGeoDb爲空。檢查ListeToponymesGeoDb是否正確填充。 – WithMetta

+0

只需投入一個getter屬性中的'IReadOnlyCollection '。 – ja72

回答

0

保留一個項目的私人列表,並公開IReadOnlyCollection的屬性。

public struct Topo { } 

public class Foo 
{ 
    // Private list of types. This is actual storage of the data. 
    // It is inialized to a new empty list by the constructor. 
    private List<Topo> InnerItems { get; } = new List<Topo>(); 

    // Example on how to modify the list only through this class 
    // Methods have access to `InnerList` 
    public void Add(Topo item) { InnerItems.Add(item); } 

    // Outside of the class only `Items` is exposed 
    // This poperty casts the list as a readonly collection 
    public IReadOnlyCollection<Topo> Items => InnerItems; 
} 

class Program 
{ 
    static void Main(string[] args) 
    { 
     var foo = new Foo(); 

     foo.Add(new Topo()); 

     // foo.Items.Add() doesnt exist. 

     foreach(var item in foo.Items) 
     { 
      Console.WriteLine(item); 
     } 
    } 
} 

或者,您可以改用以下內容:

public IReadOnlyList<Topo> Items => InnerItems; 

這使您可以通過索引訪問的結果也。像第一個項目Items[0]一樣。