[英]How can I make a function that loops over a list and takes which data member to access as input parameter
I have a datatype PlayerStats which contains a lot of different data members. 我有一个包含很多不同数据成员的数据类型PlayerStats。 I want to calculate a score which is different for each data member (the case below looks at statistics.nrOfGoals).
我想计算一个分数,该分数对于每个数据成员都是不同的(下面的情况是statistics.nrOfGoals)。
private double getScore()
{
double strength = 0;
foreach (PlayerStats statistics in this.statistics)
{
double dateDiff = Math.Abs(nowDate.Subtract(statistics.date).Days / (365.25 / 12));
dateDiff = Math.Pow(dateDiff, Form1.historyFactor);
strength += (statistics.nrOfGoals * ValueTable.PointsPerGoals ) / dateDiff;
}
return strength;
}
How can I make this function general and accept which datamember to look at instead of creating a lot of similar looking functions? 我如何才能使此函数具有通用性并接受要查看的数据成员,而不是创建许多相似的函数?
Something like 就像是
private double getScore(Type type, Type type2)
{
double strength = 0;
foreach (PlayerStats statistics in this.statistics)
{
double dateDiff = Math.Abs(nowDate.Subtract(statistics.date).Days / (365.25 / 12));
dateDiff = Math.Pow(dateDiff, Form1.historyFactor);
strength += (statistics.type * ValueTable.type2) / dateDiff;
}
return strength;
}
You can give a function as a parameter with signature PlayerStats -> Double
: 您可以使用签名
PlayerStats -> Double
来给函数提供参数:
private double getScore(Func<PlayerStats,double> type, double type2)
{
double strength = 0;
foreach (PlayerStats statistics in this.statistics)
{
double dateDiff = Math.Abs(nowDate.Subtract(statistics.date).Days / (365.25 / 12));
dateDiff = Math.Pow(dateDiff, Form1.historyFactor);
strength += (type(statistics) * type2) / dateDiff;
}
return strength;
}
And then call it with: 然后调用:
getScore(x => x.nrOfGoals,ValueTable.PointsPerGoals);
x => x.nrOfGoals
is a lambda-expression that defines some kind of function that (in this case) takes as input a PlayerStats
instance and returns a double
. x => x.nrOfGoals
是一个lambda表达式 ,它定义某种函数(在这种情况下)将PlayerStats
实例作为输入并返回double
。
In the code, you can then see type
as a "function"/"method" and call it with type(y)
(with y
a PlayerStats
instance). 然后,在代码中,您可以将
type
视为“函数” /“方法”,并使用type(y)
(带有y
的PlayerStats
实例)对其进行PlayerStats
。
您可以将属性名称作为字符串参数,并使用反射按名称查找属性。
You can pass Func<PlayerStats, double>
to your function, like: 您可以将
Func<PlayerStats, double>
传递给函数,例如:
private double getScore(Func<PlayerStats, double> evaluator)
{
double strength = 0;
foreach (PlayerStats statistics in this.statistics)
{
double dateDiff = Math.Abs(nowDate.Subtract(statistics.date).Days / (365.25 / 12));
dateDiff = Math.Pow(dateDiff, Form1.historyFactor);
strength += evaluator(statistics) / dateDiff;
}
return strength;
}
And then call it like (in your shown case) 然后称呼它(在您显示的情况下)
getScore(x => x.nrOfGoals * ValueTable.PointsPerGoals);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.