2012-10-29 36 views
2

我有一个object它有一些属性,其中一些属性是Lists。每个列表都包含其他类的实例。我想要做的是从列表中获取第一项并覆盖这些属性值。C# - 使用新对象值更新列表项目

这里是什么,我有一个伪例如:

public class User 
{ 
    public List<Address> Addresses = new List<Address>(); 

    public User () 
    { 
     Addresses = fill with data; 
    } 
} 


public class TestUser 
{ 
    public User user; // Is filled somewhere in this class 

    public void TestUpdateList (Address addr) 
    { 
     // The param "addr" contains new values 
     // These values must ALWAYS be placed in the first item 
     // of the "Addresses" list. 

     // Get the first Address object and overwrite that with 
     // the new "addr" object 
     user.Addresses[0] = addr; // <-- doesn't work, but should give you an idea 
    } 
} 

我希望这个例子阐明了我想要做一些轻。

所以我基本上在寻找一种方式来“更新”列表中的现有项目,在这种情况下是object

+1

究竟不到风度的工作? TestUser不应该在里面保存一个User的实例吗? – Blachshma

+0

它为什么不起作用?你能提供有关错误的更多细节吗? – Dutts

+0

地址是类还是结构? – sll

回答

0

这是不完全清楚你所要完成的是什么,但是,请看下面的代码 - 有一个地址,用户和一个名为FeatureX的实用程序,用一个给定值替换用户的第一个地址。

class Address { 
    public string Street { get; set; } 
} 

class User { 
    public List<Address> Addresses = new List<Address>(); 
} 

class FeatureX { 
    public void UpdateUserWithAddress(User user, Address address) { 
     if (user.Addresses.Count > 0) { 
      user.Addresses[0] = address; 
     } else { 
      user.Addresses.Add(address); 
     } 
    } 
} 

下使用输出“XYZ”两次:

User o = new User(); 
Address a = new Address() { Street = "Xyz" }; 

new FeatureX().UpdateUserWithAddress(o, a); 
Console.WriteLine(o.Addresses[0].Street); 

o = new User(); 
o.Addresses.Add(new Address { Street = "jjj" }); 
new FeatureX().UpdateUserWithAddress(o, a); 
Console.WriteLine(o.Addresses[0].Street); 

要知道,公共领域可能会导致很多麻烦,如果你与第三方共享您的DLL。

0

您的示例不会编译,因为您正在通过类名访问Addresses属性。这是唯一可能的,如果它是静态的。所以你需要一个用户的情况下第一,更新他的地址:

User u = new User(userID); // assuming that theres a constructor that takes an identifier 
u.Addresses[0] = addr; 

C# Language Specification: 10.2.5 Static and instance members

0

我认为问题是地址是一个私人领域。

这工作:

[TestFixture] 
public class ListTest 
{ 
    [Test] 
    public void UpdateTest() 
    { 
     var user = new User(); 
     user.Addresses.Add(new Address{Name = "Johan"}); 
     user.Addresses[0] = new Address { Name = "w00" }; 
    } 
} 
public class User 
{ 
    public List<Address> Addresses { get;private set; } 

    public User() 
    { 
     Addresses= new List<Address>(); 
    } 
} 
public class Address 
{ 
    public string Name { get; set; } 
} 
0
public void TestUpdateList (User user, Address addr) 
    { 
     // The param "addr" contains new values 
     // These values must ALWAYS be placed in the first item 
     // of the "Addresses" list. 

     // Get the first Address object and overwrite that with 
     // the new "addr" object 
     user.Addresses[0] = addr; // <-- doesn't work, but should give you an idea 
    }