gpt4 book ai didi

c# - 请帮助我了解匿名代表?

转载 作者:行者123 更新时间:2023-11-30 19:33:39 26 4
gpt4 key购买 nike

我已经从 Microsoft 下载了 VCSharpSample 包并开始阅读关于匿名代表的内容。我或多或少能理解代码在做什么,但我不明白背后的原因。也许如果你给我一些例子,它会导致更清晰的代码和更容易的可维护性,那么我可以全神贯注。 :)

你能帮忙吗?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
delegate decimal CalculateBonus(decimal sales);

class Player
{
public string Name;
public decimal Score;
public decimal Bonus;
public CalculateBonus calculation_algorithm;
}

class Program
{
static decimal calculateStandardBonus(decimal sales)
{
return sales / 10;
}

static void Main(string[] args)
{
decimal multiplier = 2;

CalculateBonus standard_bonus = new CalculateBonus(calculateStandardBonus);
CalculateBonus enhanced_bonus = delegate(decimal sales) { return multiplier * sales / 10; };

Player[] players = new Player[5];

for (int i = 0; i < 5; i++)
{
players[i] = new Player();
}

players[0].Name = "Sergio";
players[0].Score = 240;
players[0].calculation_algorithm = standard_bonus;

players[1].Name = "Sergio";
players[1].Score = 240;
players[1].calculation_algorithm = enhanced_bonus;

players[2].Name = "Caro";
players[2].Score = 89;
players[2].calculation_algorithm = standard_bonus;

players[3].Name = "Andy";
players[3].Score = 38;
players[3].calculation_algorithm = enhanced_bonus;

players[4].Name = "Hugo";
players[4].Score = 600;
players[4].calculation_algorithm = enhanced_bonus;

foreach (Player player in players)
{
PerformCalculationBonus(player);
}

foreach (Player player in players)
{
DisplayPersonalDetails(player);
}

Console.ReadLine();
}

public static void PerformCalculationBonus(Player player)
{
player.Bonus = player.calculation_algorithm(player.Score);
}

public static void DisplayPersonalDetails(Player player)
{
Console.WriteLine(player.Name);
Console.WriteLine(player.Score);
Console.WriteLine(player.Bonus);
Console.WriteLine("---------------");
}
}
}

最佳答案

匿名委托(delegate)旨在通过能够在另一个方法中内联定义简单委托(delegate)的行为来帮助您提高代码的可读性。这意味着如果您正在处理需要委托(delegate)的事情(例如事件处理程序),您可以直接在代码中定义行为,而不是为其创建专用函数。

此外,它们是 lambda 表达式的前身。 LINQ to Objects(对 IEnumerable<T> 进行操作的任何方法)之类的东西使用委托(delegate)对对象执行查询。例如,如果您有一个字符串集合并且您想要一个查询来查找所有长度为五个字符的字符串,您可以使用 lambda 来实现:

List<string> strings = ...

var query = strings.Where(s => s.Length == 5);

或者您可以通过匿名委托(delegate)来完成:

var query = strings.Where(delegate(string s) { return s.Length == 5; });

如果您没有这些,您的代码将如下所示:

var query = strings.Where(IsFiveCharacters);

...

private bool IsFiveCharacters(string input)
{
return input.Length == 5;
}

不过,重要的是要认识到 lambda 和匿名委托(delegate)只是编译器功能。当您的代码被编译时,它确实实际上像上一个示例一样创建了常规函数,但它们被隐藏并使用在所用语言中非法的字符命名。在执行闭包(您访问存在于 lambda/匿名委托(delegate)声明之外的变量)之类的事情时,也有很多逻辑围绕着它们。

关于c# - 请帮助我了解匿名代表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3266731/

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