- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我一直在努力了解 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 种不同的方法:
ProcessPaperbackBooksWithDelegate
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
是示例中已有的函数。 Main2
和Main3
是我加的fiddles。
如我所料,Main1
和 Main2
给出相同的结果,即:
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
它可能与这个问题无关,但为什么不能这样做呢?这似乎是一个非常直接的类型推导。
最佳答案
Func
和 Action
Func
和/或 Action
当您可以使用 delegate
获得相同的结果时?因为:
Func
和 Action
这是编写代码的惯用方式。除非有令人信服的相反理由,否则您想入乡随俗。让我们看看问题是什么:
// 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"
最后一行是有问题的:没有技术原因不能工作,但编译器会处理 Foo
和 Bar
作为不同的类型,他们是不允许的。这可能会导致摩擦,因为如果你只有一个 Bar
你必须写
var bar = new Bar(delegate() {});
Consumer(new Foo(bar)); // OK, but the ritual isn't a positive experience
Func
上使用委托(delegate)和/或 Action
?因为:
Func<List<Dictionary<int, string>>, IEnumerable<IEnumerable<int>>>
.因为我认为这两种情况都很少发生,所以在日常使用中,实际的答案是“根本没有理由”。
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
使用非 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# 团队不允许它工作的两个原因:
IsInteresting(int)
的代码引入编译错误因为你添加了一个 IsInteresting(string)
会给人留下非常糟糕的印象。关于c# - 在方法签名中使用委托(delegate)和使用 Func<T>/Action<T> 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18740815/
我有一个加载 View 的 View ,需要将 View 推送到主导航 Controller 。 我已经为每个 View 设置了一个委托(delegate),并且基本上使我的调用沿着“链”返回到主导航
我通过 NSURLConnction 从服务器获取数据,并希望从获取的数组中填充表格 View 。数据出现在 NSURLConnection 委托(delegate)方法的日志中,但我意识到 numb
我已经将我用作标题 View 的 View 子类化,它里面有一些按钮委托(delegate),它工作得很好。 但是,我在 viewController 上方展示了一个 modalViewControl
我希望这听起来像是一个显而易见的问题,但是委托(delegate)返回类型是否也必须与其委托(delegate)的方法的返回类型相匹配? EG,像这样: public static void Save
我想使用 Kotlin 委托(delegate),但我不想在委托(delegate)人之外创建委托(delegate)。委托(delegate)的所有示例都如下所示: interface Worker
我有一个问题: - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInf
伙计们。我正在寻求帮助。这似乎是一个非常简单的任务,但我可以解决一整天。我正在尝试使用容器 View 创建侧面菜单。当用户按下“更多”按钮(barButtonItem)时,整个 View 向右滑动并出
我正在努力将 UIWebView 迁移到 WKWebView。我已经更改了所有委托(delegate)方法。我需要 WKWebView 委托(delegate)方法等于下面的 UIWebView 委托
我正在学习 VB.NET 中的委托(delegate),但对委托(delegate)类型感到困惑。在阅读有关委托(delegate)的内容时,我了解到委托(delegate)是一种数据类型,可以引用具
我有一个用 Objetive-C 构建的框架。该框架用于连接蓝牙设备并与之交互。 在演示代码中,Objetive-C 委托(delegate)函数如下所示。演示代码由框架创建者提供。 -(void)b
//NewCharts.h #import @interface NewCharts : UIViewController @property(nonatomic,retain)IBOutlet U
我正在努力了解 async/await 并认为我确实了解有关用法的一些事情。但仍然不太清楚在下面的场景中实际好处是什么。 查看 Task.Run 用法。第一种方法使用普通委托(delegate)并使用
我已经尝试了在我的网站上使用 openID 委托(delegate)的所有可能选项,但没有一个方法对我有用。 我的 HTML 文件的 head 部分有“link rel”标签。 我在 HTML 文件的
如何快速创建一个委托(delegate),即 NSUserNotificationCenterDelegate? 最佳答案 这里有一些关于两个 View Controller 之间委托(delegat
我有一个带有数据源的 NSComboBox,当您单击三角形并通过单击它选择其中一个项目时,它可以完美运行。但是,我还希望它允许用户在框中键入以使用自动完成来选择名称。目前,当用户键入时,我希望选择的项
我在代码中定义了以下类和委托(delegate)(为简洁起见,剪掉了许多其他行)。 Public Delegate Sub TimerCallback(canceled As Boolean) Pub
我使用 ansible 2.1 并且我想使用 delegate_to 向一组主机运行命令。我使用 localhost 作为主机参数,并且我想将“touch”命令委托(delegate)给两个 cls
我想通过重载为我的类实现几个构造函数。据我了解,遵循 DRY 原则的惯用方式是使用一种称为委托(delegate)构造函数的功能。我也看到了关于在任何地方使用引用参数并不惜一切代价避免使用指针的想法,
代表们会导致内存泄漏吗? 我的意思是,例如如果一个类A包含一个ADelegate,并且后者指向BMethod(属于B类),这可以防止GC收集A类或B类吗? 如果是这样,我们如何“释放”代表(设置ADe
委托(delegate)命令和路由命令有什么区别? 我读了一些文章说在 MVVM 上使用委托(delegate)命令而不是路由命令。 那么当我们使用 MVVM 时,Delegate Command 相
我是一名优秀的程序员,十分优秀!