委托使用(方法)

Delegate using (methodes)

我正在尝试与代理人一起工作,但是我不知道如何正确使用它们。 我想知道它们的用途。

namespace Delegates_Events_Excptions
{
    public class Program
    {
        static void Main(string[] args)
        {

            PlayerStats.ScoreDelegate scoreDelegate = new PlayerStats.ScoreDelegate(PlayerStats.OnGameOver(allPlayerStats));
            Console.WriteLine(scoreDelegate);
            Console.ReadKey();
        }

        /// <summary>
        ///  Here in this tutorial you get to know the difference between using delegates and not
        ///  You safe a lot of Time and code when u do so
        ///  You can use it when you use two or more methods that do the same with different values
        /// </summary>
        public class PlayerStats
        {
            public string name;
            public int health;
            public int dmg;
            public int gold;

            public delegate int ScoreDelegate(PlayerStats stats);

            public static void OnGameOver(PlayerStats[] allPlayerStats)
            {
                int playerNameMostHealth = GetPlayerNameTopScore(allPlayerStats, stats => stats.health) ;
                int playerNameMostGold = GetPlayerNameTopScore(allPlayerStats, stats => stats.gold);
                int playerNameMostDmg = GetPlayerNameTopScore(allPlayerStats, stats => stats.dmg);
            }

            public static int GetPlayerNameTopScore(PlayerStats[] allPlayerStats, ScoreDelegate scoreCalculator)
            {
                string name = "";
                int bestScore = 0;

                foreach (PlayerStats stats in allPlayerStats)
                {
                    int score = scoreCalculator(stats);

                    if (score > bestScore)
                    {
                        bestScore = score;
                        name = stats.name;
                    }
                }

                return bestScore;
            }
        }
}

我收到错误:CS7036 没有任何参数,"Program.PlayerStats.OnGameOver(Program.PlayerStats[])" 的形式参数 "allPlayerStats" 符合。
我已经谢谢你了:)

方法 void OnGameOver(PlayerStats[] allPlayerStats) 与委托 int ScoreDelegate(PlayerStats stats); 不兼容,因为参数类型不同。

你需要改变这个

public delegate int ScoreDelegate(PlayerStats stats);

public delegate int ScoreDelegate(PlayerStats[] stats);

这修复了错误 CS7036

接下来您需要做的事情:

  1. define allPlayerStats
  2. add attributes health, gold and dmg to class PlayerStats.

I get the error: CS7036 There isn´t any argument, that the formal parameter "allPlayerStats" from"Program.PlayerStats.OnGameOver(Program.PlayerStats[])" conforms.

是的,没错。行

PlayerStats.ScoreDelegate scoreDelegate = new PlayerStats.ScoreDelegate(PlayerStats.OnGameOver(allPlayerStats));

由于几个原因无效。首先,这个范围内没有 allPlayerStats 这样的变量;其次,PlayerStats.OnGameOver(allPlayerStats) 不是一个函数,所以你不能用它做一个 ScoreDelegate

你想用这条线完成什么?因为我不知道你想要完成什么,所以我只能猜测你需要做什么才能完成它。

但我猜测您想要:

  • 修改函数 PlayerStats.OnGameOver 使其 returns 一些东西。
  • 删除变量 scoreDelegate,因为它没有任何用途。
  • PlayerStats.OnGameOver的结果值调用Console.WriteLine