次のようにリストの最初のアイテムを取得できます。
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のカプセル化のすべての魔法です。