私は .net の初心者です。生地のパターン方法を理解しようとしています。
私はこのコード例を見つけました:
public abstract class Person
{
public string Name { get; set; }
public decimal Salary { get; set; }
}
public class Employee : Person
{
public Employee()
{
this.Salary = 20000;
}
}
public class Pilot : Person
{
public string PilotNumber { get; set; }
public Pilot()
{
this.Salary = 50000;
}
}
public static class PersonFactory
{
public static Person CreatePerson(string typeOfPerson)
{
switch (typeOfPerson)
{
case "Employee":
return new Employee();
case "Pilot":
return new Pilot();
default:
return new Employee();
}
}
}
ファクトリを使用するには:
Person thePilot = PersonFactory.CreatePerson("Pilot");
((Pilot)thePilot).PilotNumber = "123ABC";
この例の CreatePerson メソッドが理解できません。
public static Person CreatePerson(string typeOfPerson)
{
switch (typeOfPerson)
{
case "Employee":
return new Employee();
case "Pilot":
return new Pilot();
default:
return new Employee();
}
}
このメソッドは Person タイプを返しますが、スイッチ演算子では、Pilot() または Employee() インスタンス クラスを作成して返します。
メソッドのシグネチャの戻り値の型の定義が、関数自体の戻り値の型と異なるのはどうしてでしょうか。