2

我有一个包含许多不同数据成员的数据类型 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;
}
4

3 回答 3

4

您可以将函数作为带有签名的参数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 表达式,它定义了某种函数,(在这种情况下)将一个PlayerStats实例作为输入并返回一个double.

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

于 2015-01-21T13:58:17.110 回答
1

您可以将属性名称作为字符串参数,并使用反射按名称查找属性。

于 2015-01-21T13:58:19.313 回答
1

您可以传递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;
}

然后像这样称呼它(在你展示的情况下)

getScore(x => x.nrOfGoals * ValueTable.PointsPerGoals);
于 2015-01-21T13:59:08.530 回答