如果我一直在正确地研究这个,我之前得到了一些帮助,一个用户说使用 Dictionary
来存储我的 Country
和 地点
。
所以我创建了我的 Dictionary
:
Dictionary<string, NewCountryClass> NTCD = new Dictionary<string, NewcountryClass>();
当用户单击按钮时,它将触发此类,我希望它在运行时在 Dictionary
中创建 newCountryClass
的实例。它将添加字符串,即 newCountryTitle.Country
,然后是 Class
。
public void AddCountryCollection()
{
newCountryClass = new NewCountryClass(newCountry,"");
Collections.Add(newCountryClass);
NTCD.Add(newCountryClass.Country, newCountryClass);
}
假设用户在运行时添加了创建这个Dictionary
的Country
,并且他们添加了4个 Countries
,但现在想返回并在第二个 Country 中添加 Place
标签。
这是 newCountryClass
:
private string _country;
public string Country
{
get { return _country; }
set
{
if (_country.Equals(value))
return;
_country= value;
RaisePropertyChanged(() => Country);
}
}
private ICollection<string> _places;
public ICollection<string> Places
{
get
{
if (_places== null)
_places= new ObservableCollection<string>();
return _places;
}
set
{
if (value == _places)
return;
_places= value;
RaisePropertyChanged(() => Places);
}
}
如果他们创建了 4 个,并且他们想在他们创建的第二个 的 Country
内的列表中添加一个 Place
,我怎样才能找到它?
最佳答案
只需使用您存储的 key :
NTCD["GER"].Places.Add("New Place inside GER");
如果你只想知道第二个,要么拿List<NewCountryClass>
并使用 for
按索引迭代或采取 OrderedDictionary
.它在添加时将对象键、对象值作为参数,您可以通过 NTCD[3]
访问它。 .
关于c# - 如何在字典中查找类的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21336547/