首先,我将创建一个 Person 类:
public class Person
{
string _initials = "";
public String FirstName { get; set; }
public String LastName { get; private set; }
public String MiddleName { get; private set; }
public String Initials { get { return _initials; } }
public String FullName { get { return FirstName + MiddleName + LastName; } }
public Person(String name)
{
string[] names = name.Split(' ');
if (names.Length != 3)
{
throw new ArgumentException("Incorrect format for a person.");
}
FirstName = names[2];
MiddleName= names[1];
LastName = names[0];
_initials =
String.Concat(LastName[0],LastName[1],MiddleName[0],FirstName[0]);
}
}
然后用文件填充 Person 类:
List<Person> personsList = new List<Person>();
using (StreamReader reader = new StreamReader(filePath))
{
while (!reader.EndOfStream)
{
Person p = new Person(reader.ReadLine());
personsList.Add(p);
}
}
然后您可以访问 Person 的名字、姓氏和中间名以及他们的首字母:
foreach(Person p in personsList)
{
Console.WriteLine(p.Initials);
}