【问题标题】:How to add a string to a ICollection<string>?如何将字符串添加到 ICollection<string>?
【发布时间】:2014-01-27 10:09:00
【问题描述】:

编辑 2

在过去的几天里,我在尝试解决的一个问题上得到了一些帮助。在获得了多位用户的帮助后,我遇到了一个错误,我在周末一直在尝试修复,但仍然没有成功。

我创建了一个字典,我在其中传递了一个 string Country 和一个 ICollection 该国家/地区的 Places。

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);
  }
}

这是可以添加地点的地方,但我在添加 Country 阶段创建了我的类的实例,因此当时无法传递地点。 (编辑 - 我已将集合的初始化移到构造函数中,而不是按照建议移到 Places 属性中)。

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

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

因此,我尝试创建一个renamePlace() 方法:

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

然而,_places 似乎仍然为空,即使有此尝试。任何进一步的想法或我做错了什么?

【问题讨论】:

  • 不应该在 NewCountryClass 构造函数中使用 Property Places 而不是字段 _places 吗?然后 _places 字段将被初始化。
  • @twrowsell 但是正如您在places 属性的get 部分中看到的那样,_places 已经过验证并且仍然返回null。
  • 只是为了澄清,在构造函数中它测试地方 != null 。我看不到所指的字段或变量。您有一个字段 _places 和一个属性 Places。应该是 _places 吗?
  • @twrowsell 看看我添加到 Sheridans 答案中的评论,这应该可以解释。
  • -1 用于更改您的代码,使当前的 cmets 和答案不再有意义

标签: c# wpf class mvvm icollection


【解决方案1】:

您需要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,并确保它在您的程序的这个阶段具有价值。

【讨论】:

  • 编辑了我的问题。我无法将AddCountryCollection 中的位置传递给构造函数,因此这就是为什么_places 在我实例化时仍然为空,_places 没有传递字符串值。我尝试添加一个方法来分别传递 _questions 一个字符串值,但仍然出错并且有一个空值。
【解决方案2】:

在构造函数中初始化 _places 集合而不是属性 get 访问器不是更好吗?

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

}

【讨论】:

  • 感谢您的回答,我已将集合移至构造函数,但即使在调用 RenamePlace() 方法之后,_places 仍然存在集合中没有任何内容的问题。
  • RenamePlace 是 NewCountryClass 的成员函数吗?
  • 是的,它在同一类。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-04
  • 2015-04-09
  • 1970-01-01
  • 1970-01-01
  • 2010-11-29
  • 2015-07-15
  • 2017-03-09
相关资源
最近更新 更多