簡體   English   中英

對於類的每個實例,類方法可以具有不同的代碼嗎?

[英]Can a class method have different code for each instance of the class?

我想創建一個具有成員函數(例如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);

我想到了兩種主要方法:

1)給每個人一個定義功能的代表:

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

然后,您只需要弄清楚如何設置它,並確保在使用前始終設置好它。 可以這樣說:

int charityAmount = CharityFunction();

2)使Person成為abstract類。 添加一個抽象函數,如int getCharityAmount() 然后創建新的子類型,每個子類型都提供該抽象功能的不同實現。

至於使用哪種,將更多地取決於具體情況。 您是否有許多不同的功能定義? 第一個選項只需花費較少的精力即可添加新的選項。 創建對象后功能是否會發生變化? 第二種選擇,只有第一種是不可能的。 您會重復使用相同的功能嗎? 在這種情況下,第二種選擇更好,這樣,調用者就不會不斷地重新定義相同的少數幾個函數。 第二個方法也更安全一些,因為該函數將始終具有定義,並且您知道一旦創建對象就不會更改它,等等。

為什么不通過傳入實現不同的giveCharity(Person friend)方法的函數對象Charity來構造Person對象。

然后person.giveCharity(Person friend)可以簡單地調用my_charity.giveCharity(friend)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM