Skip to main content
 首页 » 编程设计

c#之替换作为属性/公共(public)字段检索的对象列表中的元素

2024年02月06日14think

我正在尝试做一件简单的事情——将列表中的一个对象替换为另一个“更新的”对象。问题是实际列表没有得到更新。列表已定义并存储在我的 DataProvider 类中:

public class CountriesDataSet 
{ 
    List<Country> b; 
    private IXmlBinder xmlBinder; 
 
    public CountriesDataSet() 
    {             
        xmlBinder = new BasicXmlLoader(); 
        Countries = xmlBinder.Load(); 
    } 
 
    public List<Country> Countries;         
 
    public void Save() 
    { 
        xmlBinder.Save(Countries); 
    } 
} 

用法在另一个类中,我们称之为 Controller ,我在其中存储我的 CountriesDataSet 类的实例。

我正在尝试在那里进行更新:

  var countries = countriesDataSet.Countries; 
 
  Country country = countries.First(c => c.Id == id); 
 
  if (country != null) 
  {                     
      country = newCountry; 
      countriesDataSet.Save();                     
  } 

我可以看到国家被 newCountry 的新实例所取代,但是 countriesDataSet.Countries 没有更新,我做错了什么?解决这个问题的正确方法是什么?

请您参考如下方法:

用newCountry更新country的信息

例子:

var countries = countriesDataSet.Countries; 
Country country = countries.First(c => c.Id == id); 
if (country != null) 
{                     
 country.State = newCountry.State; 
 country.Flag = NewCountry.Flag; 
 ... 
 countriesDataSet.Save();                     
} 

或者那样 :

int index = listofelements.IndexOf(oldValue); 
if(index != -1) 
    listofelements[index] = newValue;