Rob*_*nes 1 c# methods artificial-intelligence class member-functions
我想用一个成员函数(例如,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);
Run Code Online (Sandbox Code Playgroud)
有两种主要方法可供考虑:
1)给每个人一个定义功能的代表:
public Func<int> CharityFunction{get;set;}
Run Code Online (Sandbox Code Playgroud)
然后你只需要弄清楚如何设置它,并确保在使用它之前始终设置它.打电话就说:
int charityAmount = CharityFunction();
Run Code Online (Sandbox Code Playgroud)
2)制作Person的abstract类.添加一个抽象函数int getCharityAmount().然后创建新的子类型,每个子类型提供该抽象函数的不同实现.
至于使用哪个,这将更多地取决于细节.你有很多不同的功能定义吗?第一个选项需要花费更少的精力来添加新的选项.在创建对象后,该功能是否会发生变化?第二种选择是不可能的,只有第一种选择.你重复使用相同的功能吗?在这种情况下,第二种选择更好,因此呼叫者不会不断地重新定义相同的少量功能.第二个也更安全一点,因为函数将始终具有定义,并且您知道一旦创建对象,它将不会被更改,等等.