在 C# 中将对象添加到列表后,如何操作对象的属性

本文关键字:对象 何操作 操作 属性 添加 列表 | 更新日期: 2023-09-27 17:57:06

假设我有这样的类:

class public Person
{
    public string firstName;
    public string lastName;
    public string address;
    public string city;
    public string state;
    public string zip;
    public Person(string firstName, string lastName)
    {
        this.firstName = firstName;
        this.lastName = lastName;
    }
}

让我们进一步假设我创建了一个类型的 Person 列表,如下所示:

List<Person> pList = new List<Person>;
pList.Add(new Person("Joe", "Smith");

现在,我想为 Joe Smith 设置地址、城市、州和邮政编码,但我已经将该对象添加到列表中。 那么,在将对象添加到列表中,如何设置这些成员变量呢?

谢谢。

在 C# 中将对象添加到列表后,如何操作对象的属性

您将该项目从列表中移回,然后设置它:

pList[0].address = "123 Main St.";

您可以保留对对象的引用。尝试像这样添加:

List<Person> pList = new List<Person>;
Person p = new Person("Joe", "Smith");
pList.Add(p);
p.address = "Test";

或者,您可以直接通过列表访问它。

pList[0].address = "Test";

您可以像这样获取列表的第一项:

Person p = pList[0];Person p = pList.First();

然后,您可以根据需要对其进行修改:

p.firstName = "Jesse";

另外,我建议使用自动属性:

class public Person
{
    public string firstName { get; set; }
    public string lastName { get; set; }
    public string address { get; set; }
    public string city { get; set; }
    public string state { get; set; }
    public string zip { get; set; }
    public Person(string firstName, string lastName)
    {
        this.firstName = firstName;
        this.lastName = lastName;
    }
}

你会得到相同的结果,但是当你想要验证输入或更改设置项目的方式的那一天,它会简单得多:

class public Person
{
    private const int ZIP_CODE_LENGTH = 6;
    public string firstName { get; set; }
    public string lastName { get; set; }
    public string address { get; set; }
    public string city { get; set; }
    public string state { get; set; }
    private string zip_ = null;
    public string zip 
    { 
        get { return zip_; } 
        set
        {
            if (value.Length != ZIP_CODE_LENGTH ) throw new Exception("Invalid zip code.");
            zip_ = value;
        }
    }
    public Person(string firstName, string lastName)
    {
        this.firstName = firstName;
        this.lastName = lastName;
    }
}

当您在此处设置属性时,很可能不是崩溃的最佳决定,但您可以大致了解能够快速更改对象的设置方式,而无需在任何地方调用 SetZipCode(...); 函数。这是封装OOP的所有魔力。

您可以通过项目的索引访问该项目。如果要查找最后添加的项目,则可以使用列表的长度 - 1:

List<Person> pList = new List<Person>;
// add a bunch of other items....
// ....
pList.Add(new Person("Joe", "Smith");
pList[pList.Length - 1].address = "....";

如果忘记了列表中要查找的元素,则始终可以使用 LINQ 再次查找该元素:

pList.First(person=>person.firstName == "John").lastName = "Doe";

或者,如果您需要一次重新定位所有"Doe",您可以执行以下操作:

foreach (Person person in pList.Where(p=>p.lastName == "Doe"))
{
    person.address = "Niflheim";
}