【发布时间】:2019-08-15 15:32:36
【问题描述】:
我想与代表一起工作,但我不知道如何正确使用它们。 我想知道它们的用途。
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”符合。
我已经谢谢你了:)
【问题讨论】:
标签: c# visual-studio methods delegates overloading