gpt4 book ai didi

c# - 在方法签名中使用委托(delegate)和使用 Func/Action 有什么区别?

转载 作者:可可西里 更新时间:2023-11-01 08:01:21 24 4
gpt4 key购买 nike

我一直在努力了解 C# 中的委托(delegate),但我似乎不明白使用它们的意义。这是来自 MSDN 的一些稍微重构的代码委托(delegate)页面:

using System;
using System.Collections;

namespace Delegates
{
// Describes a book in the book list:
public struct Book
{
public string Title; // Title of the book.
public string Author; // Author of the book.
public decimal Price; // Price of the book.
public bool Paperback; // Is it paperback?

public Book(string title, string author, decimal price, bool paperBack)
{
Title = title;
Author = author;
Price = price;
Paperback = paperBack;
}
}

// Declare a delegate type for processing a book:
public delegate void ProcessBookDelegate(Book book);

// Maintains a book database.
public class BookDB
{
// List of all books in the database:
ArrayList list = new ArrayList();

// Add a book to the database:
public void AddBook(string title, string author, decimal price, bool paperBack)
{
list.Add(new Book(title, author, price, paperBack));
}

// Call a passed-in delegate on each paperback book to process it:
public void ProcessPaperbackBooksWithDelegate(ProcessBookDelegate processBook)
{
foreach (Book b in list)
{
if (b.Paperback)
processBook(b);
}
}

public void ProcessPaperbackBooksWithoutDelegate(Action<Book> action)
{
foreach (Book b in list)
{
if (b.Paperback)
action(b);
}
}
}

class Test
{

// Print the title of the book.
static void PrintTitle(Book b)
{
Console.WriteLine(" {0}", b.Title);
}

// Execution starts here.
static void Main()
{
BookDB bookDB = new BookDB();
AddBooks(bookDB);
Console.WriteLine("Paperback Book Titles Using Delegates:");
bookDB.ProcessPaperbackBooksWithDelegate(new ProcessBookDelegate(PrintTitle));
Console.WriteLine("Paperback Book Titles Without Delegates:");
bookDB.ProcessPaperbackBooksWithoutDelegate(PrintTitle);
}

// Initialize the book database with some test books:
static void AddBooks(BookDB bookDB)
{
bookDB.AddBook("The C Programming Language",
"Brian W. Kernighan and Dennis M. Ritchie", 19.95m, true);
bookDB.AddBook("The Unicode Standard 2.0",
"The Unicode Consortium", 39.95m, true);
bookDB.AddBook("The MS-DOS Encyclopedia",
"Ray Duncan", 129.95m, false);
bookDB.AddBook("Dogbert's Clues for the Clueless",
"Scott Adams", 12.00m, true);
}
}
}

正如您在 BookDB 类中看到的,我定义了 2 种不同的方法:

  1. 一个将委托(delegate)作为参数:ProcessPaperbackBooksWithDelegate
  2. 将相应类型签名的操作作为参数:ProcessPaperbackBooksWithoutDelegate

调用它们中的任何一个都会返回相同的结果;那么委托(delegate)解决的目的是什么?

同一页上的第二个例子导致了更多的困惑;这是代码:

delegate void MyDelegate(string s);

static class MyClass
{
public static void Hello(string s)
{
Console.WriteLine(" Hello, {0}!", s);
}

public static void Goodbye(string s)
{
Console.WriteLine(" Goodbye, {0}!", s);
}

public static string HelloS(string s)
{
return string.Format("Hello, {0}!", s);
}

public static string GoodbyeS(string s)
{
return string.Format("Goodbye, {0}!", s);
}

public static void Main1()
{
MyDelegate a, b, c, d;
a = new MyDelegate(Hello);
b = new MyDelegate(Goodbye);
c = a + b;
d = c - a;

Console.WriteLine("Invoking delegate a:");
a("A");
Console.WriteLine("Invoking delegate b:");
b("B");
Console.WriteLine("Invoking delegate c:");
c("C");
Console.WriteLine("Invoking delegate d:");
d("D");
}

public static void Main2()
{
Action<string> a = Hello;
Action<string> b = Goodbye;
Action<string> c = a + b;
Action<string> d = c - a;

Console.WriteLine("Invoking delegate a:");
a("A");
Console.WriteLine("Invoking delegate b:");
b("B");
Console.WriteLine("Invoking delegate c:");
c("C");
Console.WriteLine("Invoking delegate d:");
d("D");
}

public static void Main3()
{
Func<string, string> a = HelloS;
Func<string, string> b = GoodbyeS;
Func<string, string> c = a + b;
Func<string, string> d = c - a;

Console.WriteLine("Invoking function a: " + a("A"));
Console.WriteLine("Invoking function b: " + b("B"));
Console.WriteLine("Invoking function c: " + c("C"));
Console.WriteLine("Invoking function d: " + d("D"));
}
}

Main1 是示例中已有的函数。 Main2Main3 是我加的fiddles。

如我所料,Main1Main2 给出相同的结果,即:

Invoking delegate a:
Hello, A!
Invoking delegate b:
Goodbye, B!
Invoking delegate c:
Hello, C!
Goodbye, C!
Invoking delegate d:
Goodbye, D!

Main3 然而,给出了一个非常奇怪的结果:

Invoking function a: Hello, A!
Invoking function b: Goodbye, B!
Invoking function c: Goodbye, C!
Invoking function d: Goodbye, D!

如果 + 实际上在执行函数组合,那么结果(对于 Main3)应该是:

Invoking function a: Hello, A!
Invoking function b: Goodbye, B!
Invoking function c: Hello, Goodbye, C!!
Invoking function d: //God knows what this should have been.

但很明显,+ 实际上并不是传统的功能组合(我猜,真正的组合甚至不能用于 Action)。从它似乎没有以下类型签名这一事实可以看出这一点:

(T2 -> T3) -> (T1 -> T2) -> T1 -> T3

相反,类型签名似乎是:

(T1 -> T2) -> (T1 -> T2) -> (T1 -> T2)

那么 +- 到底是什么意思?

旁白:我尝试在 Main2 中使用 var a = Hello;... 但出现错误:

test.cs(136,14): error CS0815: Cannot assign method group to an implicitly-typed
local variable

它可能与这个问题无关,但为什么不能这样做呢?这似乎是一个非常直接的类型推导。

最佳答案

自定义委托(delegate)类型与 FuncAction

为什么要用Func和/或 Action当您可以使用 delegate 获得相同的结果时?

因为:

  • 它为您省去了为每个可能的方法签名创建自定义委托(delegate)类型的麻烦。在代码中,少即是多。
  • 不同的自定义委托(delegate)类型是不兼容的,即使它们的签名完全匹配。您可以解决此问题,但它很冗长。
  • 自从引入FuncAction这是编写代码的惯用方式。除非有令人信服的相反理由,否则您想入乡随俗。

让我们看看问题是什么:

// Delegates: same signature but different types
public delegate void Foo();
public delegate void Bar();

// Consumer function -- note it accepts a Foo
public void Consumer(Foo f) {}

尝试一下:

Consumer(new Foo(delegate() {})); // works fine
Consumer(new Bar(delegate() {})); // error: cannot convert "Bar" to "Foo"

最后一行是有问题的:没有技术原因不能工作,但编译器会处理 FooBar作为不同的类型,他们是不允许的。这可能会导致摩擦,因为如果你只有一个 Bar你必须写

var bar = new Bar(delegate() {});
Consumer(new Foo(bar)); // OK, but the ritual isn't a positive experience

为什么要在 Func 上使用委托(delegate)和/或 Action

因为:

  • 您的目标是不存在这些类型的早期 C# 版本。
  • 您正在处理复杂的函数签名。没有人愿意多次输入:Func<List<Dictionary<int, string>>, IEnumerable<IEnumerable<int>>> .

因为我认为这两种情况都很少发生,所以在日常使用中,实际的答案是“根本没有理由”。

组成多播委托(delegate)

C# 中的所有委托(delegate)都是多播委托(delegate)——也就是说,调用它们可能会调用具有该签名的任意数量的方法。运营商+-不执行功能组合;他们在多播委托(delegate)中添加和删除委托(delegate)。一个例子:

void Foo() {}
void Bar() {}

var a = new Action(Foo) + Bar;
a(); // calls both Foo() and Bar()

您可以使用 operator- 从多播委托(delegate)中删除委托(delegate),但您必须传递完全相同的委托(delegate)。如果右侧操作数还不是多播委托(delegate)的一部分,则什么也不会发生。例如:

var a = new Action(Foo);
a(); // calls Foo()
a -= Bar; // Bar is not a part of the multicast delegate; nothing happens
a(); // still calls Foo() as before

多播委托(delegate)返回值

使用非 void 调用多播委托(delegate)返回类型导致多播委托(delegate)的最后添加的成员返回的值。例如:

public int Ret1() { return 1; }
public int Ret2() { return 2; }

Console.WriteLine((new Func<int>(Ret1) + Ret2)()); // prints "2"
Console.WriteLine((new Func<int>(Ret2) + Ret1)()); // prints "1"

这记录在 C# 规范中(§15.4,“委托(delegate)调用”):

Invocation of a delegate instance whose invocation list contains multiple entries proceeds by invoking each of the methods in the invocation list, synchronously, in order. Each method so called is passed the same set of arguments as was given to the delegate instance. If such a delegate invocation includes reference parameters (§10.6.1.2), each method invocation will occur with a reference to the same variable; changes to that variable by one method in the invocation list will be visible to methods further down the invocation list. If the delegate invocation includes output parameters or a return value, their final value will come from the invocation of the last delegate in the list.

旁白:“无法将方法组分配给隐式类型的局部变量”

首先你需要知道什么是方法组。规范说:

A method group, which is a set of overloaded methods resulting from a member lookup (§7.4). [...] A method group is permitted in an invocation-expression (§7.6.5), a delegate-creation-expression (§7.6.10.5) and as the left hand side of an is operator, and can be implicitly converted to a compatible delegate type (§6.6). In any other context, an expression classified as a method group causes a compile-time error.

因此,给定一个具有这两个方法的类:

public bool IsInteresting(int i) { return i != 0; }
public bool IsInteresting(string s) { return s != ""; }

当 token IsInteresting出现在源代码中,它是一个方法组(请注意,一个方法组当然可以由一个方法组成,如您的示例所示)。

编译时错误是预料之中的(规范强制要求),因为您没有尝试将其转换为兼容的委托(delegate)类型。更明确地解决了这个问题:

// both of these convert the method group to the "obviously correct" delegate
Func<int, bool> f1 = IsInteresting;
Func<string, bool> f2 = IsInteresting;

通俗地说,写var f = IsInteresting是没有意义的因为编译器唯一合理的做法是创建一个委托(delegate),但它不知道应该指向哪个方法。

在方法组只包含一个方法的特殊情况下,这个问题是可以解决的。我突然想到 C# 团队不允许它工作的两个原因:

  1. 一致性好。
  2. 如果稍后引入另一个重载,将导致完美代码的破坏。向调用 IsInteresting(int) 的代码引入编译错误因为你添加了一个 IsInteresting(string)会给人留下非常糟糕的印象。

关于c# - 在方法签名中使用委托(delegate)和使用 Func<T>/Action<T> 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18740815/

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