1

メンバー関数(giveCharityなど)を使用してクラス(Personなど)を作成したいのですが、人工知能を模倣して、クラスのインスタンスごとにそのメソッドの内容を変えたいと考えています。これは可能ですか?各インスタンスのメソッドのコードをいつどのように入力しますか?

次に例を示します。

public class Person
{
    // data members
    private int myNumOfKids;
    private int myIncome;
    private int myCash;

    // constructor
    public Person(int kids, int income, int cash)
    {
        myNumOfKids = kids;
        myIncome = income;
        myCash = cash;
    }

    // member function in question
    public int giveCharity(Person friend)
    {
        int myCharity;
        // This is where I want to input different code for each person
        // that determines how much charity they will give their friend
        // based on their friend's info (kids, income, cash, etc...),
        // as well as their own tendency for compassion.
        myCash -= myCharity;
        return myCharity;
    }
}

Person John = new Person(0, 35000, 500);
Person Gary = new Person(3, 40000, 100);

// John gives Gary some charity
Gary.myCash += John.giveCharity(Gary);
4

2 に答える 2

5

頭に浮かぶ2つの主要なアプローチがあります。

1)各人に機能を定義する代理人を与えます。

public Func<int> CharityFunction{get;set;}

次に、設定方法を理解し、使用する前に常に設定されていることを確認する必要があります。それを呼び出すには、次のように言います。

int charityAmount = CharityFunction();

2)クラスを作成Personします。abstractのような抽象関数を追加しますint getCharityAmount()。次に、それぞれがその抽象関数の異なる実装を提供する新しいサブタイプを作成します。

どちらを使用するかについては、詳細によって異なります。関数の定義はたくさんありますか?最初のオプションは、新しいオプションを追加するための労力が少なくて済みます。オブジェクトが作成された後、関数が変更されることはありますか?これは2番目のオプションでは不可能であり、最初のオプションのみです。同じ機能を何度も再利用していますか?その場合は2番目のオプションの方が適しているため、呼び出し元は同じ少数の関数を常に再定義することはありません。2つ目は、関数が常に定義を持ち、オブジェクトが作成されると変更されないことなど、少し安全です。

于 2013-01-14T21:34:44.757 に答える
0

さまざまなメソッドを実装Personする関数オブジェクトを渡して、オブジェクトを作成してみませんか。CharitygiveCharity(Person friend)

次に、person.giveCharity(Person friend)は単にを呼び出すことができますmy_charity.giveCharity(friend)

于 2013-01-14T21:32:46.483 に答える