2012-10-29 34 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 
    }