gpt4 book ai didi

c# - 如何创建一个循环遍历列表并将要访问的数据成员作为输入参数的函数

转载 作者:行者123 更新时间:2023-11-30 20:23:48 25 4
gpt4 key购买 nike

我有一个数据类型 PlayerStats,其中包含许多不同的数据成员。我想为每个数据成员计算一个不同的分数(下面的案例查看 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;
}

我怎样才能使这个函数通用并接受要查看的数据成员而不是创建很多看起来相似的函数?

有点像

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;
}

最佳答案

您可以将函数作为带有签名的参数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;
}

然后调用它:

getScore(x => x.nrOfGoals,ValueTable.PointsPerGoals);

x => x.nrOfGoals 是一个 lambda-expression它定义了某种函数(在本例中)将 PlayerStats 实例作为输入并返回 double

在代码中,您可以将 type 视为“函数”/“方法”,并使用 type(y) 调用它(使用 y 一个 PlayerStats 实例)。

关于c# - 如何创建一个循环遍历列表并将要访问的数据成员作为输入参数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28068928/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com