2014-01-27 29 views
2

編輯2如何將字符串添加到ICollection <string>?

我在過去幾天對我嘗試工作的問題有一些幫助。在得到多個用戶的有用支持後,我遇到了一個錯誤,我一直試圖在週末修復,但仍然沒有成功。

我創建了一本詞典,在那裏我通過string Country以及ICollection該國家的地方。

Dictionary<string, NewCountryClass> NTCD = new Dictionary<string, NewCountryClass>(); 

public void AddCountryCollection() 
{ 

    newCountryClass = new NewCountryClass(newCountry); 
    Collections.Add(newCountryClass); 
    NTCD.Add(newCountryClass.Country, newCountryClass); 

} 


public void AddPlace() 
{ 
    string Country = selectedItem.Country; 
    RenameQuestion(placeName); 
    NTCD[Country].Place.Add(placeName);  

} 

這是我newCountryClass在那裏我存儲在國家和地方在該國。

private ICollection<string> _places; 
public ICollection<string> Places 
{ 
    get 
    { 
     return _places; 
    } 
    set 
    { 
    if (value == _places) 
     return; 

    _places = value; 
    RaisePropertyChanged(() => Places); 
    } 
} 

這是可以添加的地方,但我在加入國家階段創建我的類的實例,因此當時不能通行的地方。 (編輯 - 我建議將集合的初始化移入構造函數而不是位置屬性中)。

public NewCountryClass(string country) 
{ 
    _places = new ObservableCollection<string>(); 

    if (country != null) 
    { 
     _country = country; 
    } 
} 

因此,我試圖創建一個renamePlace()方法:

public void RenamePlace(string place) 
{ 
    _places.Add(place); 
} 

然而,_places似乎仍然是空即使有這樣的嘗試。任何進一步的想法或我做錯了什麼?

+0

如果您不能使用物業的地方,而不是場_places在NewCountryClass構造?然後_places字段將被初始化。 – twrowsell

+0

@twrowsell但是,正如你可以在places屬性的'get'部分看到的那樣,'_places'被驗證並且仍然返回null。 – Ben

+0

只是爲了澄清,在構造函數中測試位置!= null。我看不到指向哪個字段或變量。你有一個字段_places和一個屬性Places。這應該是_places? – twrowsell

回答

0

您需要learn how to debug a program。基本上,你嘗試實例化NewCountryClass這裏:

public void AddCountryCollection() 
{         // <<< Put breakpoint here <<< 
    newCountryClass = new NewCountryClass(newCountry, placeName); 
    Collections.Add(newCountryClass); 
    NTCD.Add(newCountryClass.Country, newCountryClass);  
} 

如果placeName輸入參數的構造函數null,那麼它也是null這裏...你需要在這裏添加一個斷點,並找出爲什麼值是null,並確保它在您的程序中的這一階段具有價值。

+0

編輯我的問題。我無法將'AddCountryCollection'中的位置傳遞給構造函數,因此這就是爲什麼'_places'仍然爲null,因爲當我實例化時,'_places'沒有傳遞一個字符串值。我試着添加一個方法來傳遞_questions一個字符串值,但仍然錯誤,並有一個空值。 – Ben

0

在構造函數中初始化_places集合而不是屬性get accessor會更好嗎?

public NewCountryClass(string country) 
{ 
    _places = new ObservableCollection<string>(); 
    if (country != null) 
    { 
     _country = country; 
    } 

}

+0

感謝您的回答,我已經將集合移到了構造函數中,但即使在調用RenamePlace()方法之後,集合中沒有任何內容的'_places'仍然存在問題。 – Ben

+0

RenamePlace是NewCountryClass上的成員函數嗎? – twrowsell

+0

是的,它在同一個班級。 – Ben