0

私は .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() インスタンス クラスを作成して返します。

メソッドのシグネチャの戻り値の型の定義が、関数自体の戻り値の型と異なるのはどうしてでしょうか。

4

4 に答える 4

3

ファクトリ メソッドをジェネリック メソッドに更新すると、はるかに簡単になります。このような。

public static TPerson CreatePerson<TPerson>() where TPerson: Person {
    if (typeof(TPerson) == typeof(Employee)) {
        return new Employee();
    } else if (typeof(TPerson) == typeof(Pilot)) {
        return new Pilot();
    } else {
        return new Employee();
    }
}

次に、キャストなしで使用できます。

Pilot pilot = PersonFactory.CreatePerson<Pilot>();
pilot.PilotNumber = "123ABC";
于 2012-07-12T13:13:27.750 に答える
2

これらの戻り型はすべてPersonから継承するためです。関数から派生クラスを暗黙的に返すことができます。

public class Employee : Person <------ this Employee is inheriting the abstract class 'Person' (but not implementing anything from it)
{
    public Employee()
    {
        this.Salary = 20000;
    }

}

例:上記-Employeeクラスは、抽象クラスから継承するため、実際にはPersonでもあります(実装するものがないため、実際には抽象クラスから何も実装しません)

ここでのPersonクラスは抽象ですが、抽象メンバーを指定していません-これは単なるテストコードですか?

于 2012-07-12T13:05:02.817 に答える
1

PilotはPersonを継承しているからです。

于 2012-07-12T13:05:48.850 に答える
1

EmployeeクラスとPilotクラスは、サブクラス、または人の派生クラスです。OOPでは、これは関係に類似しています。従業員は人であり、パイロットは人であるため、これらのタイプの1つを返却することは完全に合法です。発信者は(リフレクションを使用せずに)どのタイプの人が戻ってきたかを知らないので、気にする必要はありません。

于 2012-07-12T13:05:57.040 に答える