我有以下问题:我有字符串列表。我还有一个类,它有一个名为Name的字符串属性,还有一个以字符串为参数的类的构造函数。因此,我可以通过迭代字符串列表来创建对象列表。
现在,我想更改其中一个对象的Name属性,从而自动更新原始的字符串列表。这可能吗?我不能假设字符串列表具有唯一的值。以下是一些基本代码,这些代码并不能解决我的问题,但希望能说明我需要做什么:
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
List<string> nameList = new List<string>(new string[] {"Andy", "Betty"});
List<Person> personList = new List<Person>();
foreach (string name in nameList)
{
Person newPerson = new Person(name);
personList.Add(newPerson);
}
foreach (Person person in personList)
{
Console.WriteLine(person.Name);
}
/* Note: these next two line are just being used to illustrate
changing a Person's Name property. */
Person aPerson = personList.First(p => p.Name == "Andy");
aPerson.Name = "Charlie";
foreach (string name in nameList)
{
Console.WriteLine(name);
}
/* The output of this is:
Andy
Betty
Andy
Betty
but I would like to get:
Charlie
Betty
Andy
Betty
}
public class Person
{
public string Name;
public Person(string name)
{
Name = name;
}
}
}
有人能提出解决这个问题的最佳方法吗?
如果您愿意将nameList
更改为List<Func<string>>
类型,则可以执行以下操作:
List<Person> personList =
new string[] { "Andy", "Betty" }
.Select(n => new Person(n))
.ToList();
foreach (Person person in personList)
{
Console.WriteLine(person.Name);
}
Person aPerson = personList.First(p => p.Name == "Andy");
aPerson.Name = "Charlie";
List<Func<string>> nameList =
personList
.Select(p => (Func<string>)(() => p.Name))
.ToList();
foreach (Func<string> f in nameList)
{
Console.WriteLine(f());
}
输出:
Andy
Betty
Charlie
Betty
您正在从personList
更新人员实例,并在最后打印nameList
。我想你需要交换foreach
块的顺序。