我有一个object
,它有一些属性,其中一些属性是Lists
。每个列表都包含其他类的实例。我想要做的是从列表中取出第一项并覆盖这些属性值。
这是我所拥有的一个伪示例:
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
。
答案 0 :(得分: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
答案 1 :(得分:0)
目前还不完全清楚您要完成的任务,但是,请参阅以下代码 - 有一个地址,一个用户和一个名为FeatureX的实用程序,它替换了具有给定值的用户的第一个地址。 / p>
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,公共字段可能会造成很多麻烦。
答案 2 :(得分: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; }
}
答案 3 :(得分: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
}