关于创建委托对象-C#

本文关键字:对象 -C# 创建 于创建 | 更新日期: 2023-09-27 18:20:25

我定义了一个Delegate类型,如:

delegate void DrawShape(Brush aBrush,Rectangle aRect);

你能告诉我为什么下面创建委托对象的方法都是正确的吗:

DrawShape DrawRectangleMethod = CreateGraphics().FillRectangle;
DrawShape AnotherDrawRectangleMethod = new DrawShape(CreateGraphics().FillRectangle);

为什么没有"New"的方法可以正确工作?

关于创建委托对象-C#

DrawShape DrawRectangleMethod = CreateGraphics().FillRectangle;

这要归功于C#2的隐式方法组转换,这里有详细说明。

C#足够聪明,可以为您处理方法组。方法组是不带括号的方法名称;可能有许多具有不同签名的方法重载,但没有括号的"基本"名称称为方法组。编译器将为您插入构造函数调用,使您能够编写更简洁的代码行。

因为编译器会自动为您插入它。这只是句法上的糖。

只需查看《Jons Bluffer指南》第Delegates章。