菜鸟教程 -- 学的不仅是技术,更是梦想!

C# 教程
(追記) (追記ここまで)

C# 委托(Delegate)

在 C# 中,委托(Delegate) 是一种类型安全的函数指针,它允许将方法作为参数传递给其他方法。

C# 中的委托(Delegate)类似于 C 或 C++ 中函数的指针。委托(Delegate) 是存有对某个方法的引用的一种引用类型变量,引用可在运行时被改变。

委托在 C# 中非常常见,用于事件处理、回调函数、LINQ 等操作。

所有的委托(Delegate)都派生自 System.Delegate 类。

声明委托(Delegate)

委托是一个引用类型,它定义了一个方法签名,可以用于存储指向该签名的方法。通过委托,你可以调用其他类中的方法。

委托声明决定了可由该委托引用的方法。委托可指向一个与其具有相同标签的方法。

声明委托的语法如下:

public delegate <return type> <delegate-name> <parameter list>

中文格式说明:

public delegate 返回类型 委托名(参数类型 参数名, ...);

例如以下代码,我们定义一个接受两个整数并返回一个整数的委托:

public delegate int MathOperation(int x, int y);

以下例子的委托可被用于引用任何一个带有一个单一的 string 参数的方法,并返回一个 int 类型变量。

public delegate int MyDelegate (string s);

实例化委托(Delegate)

一旦声明了委托类型,委托对象必须使用 new 关键字来创建,且与一个特定的方法有关。当创建委托时,传递到 new 语句的参数就像方法调用一样书写,但是不带有参数。例如:

public delegate void printString(string s);
...
printString ps1 = new printString(WriteToScreen);
printString ps2 = new printString(WriteToFile);

下面的实例演示了委托的声明、实例化和使用,该委托可用于引用带有一个整型参数的方法,并返回一个整型值。

实例

using System;

delegate int NumberChanger(int n);
namespace DelegateAppl
{
class TestDelegate
{
static int num = 10;
public static int AddNum(int p)
{
num += p;
return num;
}

public static int MultNum(int q)
{
num *= q;
return num;
}
public static int getNum()
{
return num;
}

static void Main(string[] args)
{
// 创建委托实例
NumberChanger nc1 = new NumberChanger(AddNum);
NumberChanger nc2 = new NumberChanger(MultNum);
// 使用委托对象调用方法
nc1(25);
Console.WriteLine("Value of Num: {0}", getNum());
nc2(5);
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}
}
}

当上面的代码被编译和执行时,它会产生下列结果:

Value of Num: 35
Value of Num: 175

委托的多播(Multicasting of a Delegate)

委托对象可使用 + 运算符进行合并。

一个合并委托调用它所合并的两个委托,只有相同类型的委托可被合并。

- 运算符可用于从合并的委托中移除组件委托。

使用委托的这个有用的特点,您可以创建一个委托被调用时要调用的方法的调用列表,这被称为委托的 多播(multicasting),也叫组播。

下面的程序演示了委托的多播:

实例

using System;

delegate int NumberChanger(int n);
namespace DelegateAppl
{
class TestDelegate
{
static int num = 10;
public static int AddNum(int p)
{
num += p;
return num;
}

public static int MultNum(int q)
{
num *= q;
return num;
}
public static int getNum()
{
return num;
}

static void Main(string[] args)
{
// 创建委托实例
NumberChanger nc;
NumberChanger nc1 = new NumberChanger(AddNum);
NumberChanger nc2 = new NumberChanger(MultNum);
nc = nc1;
nc += nc2;
// 调用多播
nc(5);
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey();
}
}
}

当上面的代码被编译和执行时,它会产生下列结果:

Value of Num: 75

委托(Delegate)的用途

下面的实例演示了委托的用法。委托 printString 可用于引用带有一个字符串作为输入的方法,并不返回任何东西。

我们使用这个委托来调用两个方法,第一个把字符串打印到控制台,第二个把字符串打印到文件:

实例

using System;
using System.IO;

namespace DelegateAppl
{
class PrintString
{
static FileStream fs;
static StreamWriter sw;
// 委托声明
public delegate void printString(string s);

// 该方法打印到控制台
public static void WriteToScreen(string str)
{
Console.WriteLine("The String is: {0}", str);
}
// 该方法打印到文件
public static void WriteToFile(string s)
{
fs = new FileStream("c:\\message.txt", FileMode.Append, FileAccess.Write);
sw = new StreamWriter(fs);
sw.WriteLine(s);
sw.Flush();
sw.Close();
fs.Close();
}
// 该方法把委托作为参数,并使用它调用方法
public static void sendString(printString ps)
{
ps("Hello World");
}
static void Main(string[] args)
{
printString ps1 = new printString(WriteToScreen);
printString ps2 = new printString(WriteToFile);
sendString(ps1);
sendString(ps2);
Console.ReadKey();
}
}
}

当上面的代码被编译和执行时,它会产生下列结果:

The String is: Hello World

移除委托

如果你不再需要某个方法,可以通过 -= 运算符将该方法从委托链中移除。

实例

public class Program
{
public delegate void PrintMessage(string message);

public static void PrintUpperCase(string message)
{
Console.WriteLine(message.ToUpper());
}

public static void PrintLowerCase(string message)
{
Console.WriteLine(message.ToLower());
}

public static void Main()
{
PrintMessage print = PrintUpperCase;
print += PrintLowerCase;

// 移除 PrintLowerCase 方法
print -= PrintLowerCase;

// 调用委托(只会调用 PrintUpperCase)
print("Hello, C#"); // 输出: HELLO, C#
}
}

委托和事件

委托常常与事件(Event)一起使用,事件是一种特殊类型的委托,用于发布和订阅机制。

在 C# 中,事件本质上就是一个封装了委托的类型,它用于响应程序中的某些操作。

实例

public class Button
{
// 定义一个事件
public event EventHandler Click;

// 引发事件的方法
public void OnClick()
{
if (Click != null)
{
Click(this, EventArgs.Empty); // 调用事件
}
}
}

public class Program
{
public static void Main()
{
Button button = new Button();

// 订阅事件
button.Click += Button_Click;

// 引发事件
button.OnClick(); // 输出 "Button clicked!"
}

private static void Button_Click(object sender, EventArgs e)
{
Console.WriteLine("Button clicked!");
}
}

委托的类型

C# 提供了几种常见的委托类型:

1、Action

Action:代表不返回值的方法。可以接受最多 16 个参数。

Action<string> printMessage = Console.WriteLine;
printMessage("Hello");

2、Func

Func:代表有返回值的方法。最多接受 16 个参数,第一个参数是输入参数,最后一个参数是返回值类型。

Func<int, int, int> add = (x, y) => x + y;
Console.WriteLine(add(3, 4)); // 输出 7

3、Predicate

Predicate:代表返回 bool 值的方法,通常用于条件判断。

Predicate<int> isEven = x => x % 2 == 0;
Console.WriteLine(isEven(4)); // 输出 True

委托的注意事项

类型安全:委托是类型安全的,这意味着只有签名匹配的方法才能赋值给委托。

匿名方法和 lambda 表达式:你可以使用匿名方法或 lambda 表达式来创建委托实例,简化代码。

Func<int, int, int> add = (x, y) => x + y;
Console.WriteLine(add(5, 3)); // 输出 8

异步调用:可以将委托与 BeginInvoke 和 EndInvoke 方法一起使用,进行异步调用。

委托是 C# 中一个非常强大和灵活的特性,可以帮助实现事件驱动的编程、回调机制和函数式编程风格。它不仅提供了代码重用的能力,还提高了程序的模块化程度。理解和掌握委托的使用对于 C# 编程是非常重要的。

AI 思考中...

4 篇笔记 写笔记

  1. #0
    511

    委托多播实例:例如小明叫小张买完车票,之后接着又让他带张电影票:

    // 小张类
    public class MrZhang
     {
     // 其实买车票的悲情人物是小张
     public static void BuyTicket()
     {
     Console.WriteLine("NND,每次都让我去买票,鸡人呀!");
     }
     public static void BuyMovieTicket()
     {
     Console.WriteLine("我去,自己泡妞,还要让我带电影票!");
     }
    }
    //小明类
    class MrMing
    {
     // 声明一个委托,其实就是个“命令”
     public delegate void BugTicketEventHandler();
     public static void Main(string[] args)
     {
     // 这里就是具体阐述这个命令是干什么的,本例是MrZhang.BuyTicket“小张买车票”
     BugTicketEventHandler myDelegate = new BugTicketEventHandler(MrZhang.BuyTicket);
     myDelegate += MrZhang.BuyMovieTicket;
     // 这时候委托被附上了具体的方法
     myDelegate();
     Console.ReadKey();
     }
    }
    
    9年前 (2017年03月10日)
  2. #0

    卫康

    310***[email protected]

    118

    定义一个委托,准备相应的调用方法。注意:定义一个委托相当于定义一个新类,所有可以定义类的地方都可以定义委托。下面的代码定义在入口所在的类下面。

    delegate double ProcessDelegate(double a, double b); // 定义一个委托。
    static double Multiply(double a, double b)
    { return a * b; }
    static double Divide(double a, double b)
    { return a / b; }
    static double Sum(double c, double d)
    { return c + d; }
    public static void Main(string[] args)
    {
     ProcessDelegete MyDelegate;
     MyDelegate = Multiply;
    }

    卫康

    310***[email protected]

    9年前 (2017年11月22日)
  3. #0

    Jenic

    856***[email protected]

    51

    委托多播实例:例如小明叫小张买完车票,之后接着又让他带张电影票。

    public delegate void DoSomeThing();
    public class MrZhang {
     public static void HelpWith(DoSomeThing callback) {
     // 小张的唯一方法,帮别人做某事;
     Console.WriteLine("小张帮====》");
     callback();
     }
    }
    public class MrMing
    {
     public static void BuyTicket() {
     Console.WriteLine("小明买了一张火车票");
     }
     public static void BuyMovieTicket() {
     Console.WriteLine("小明买了一张电影票");
     }
     public static void Main() {
     // 定义两件事,是小明需要去做的事
     DoSomeThing thing1 = new DoSomeThing(BuyTicket);
     DoSomeThing thing2 = new DoSomeThing(BuyMovieTicket);
     // 让小张去做这两件事
     thing1 += thing2;
     MrZhang.HelpWith(thing1);
     
     Console.ReadKey();
     }
    }

    输出结果:

    小张帮====》
    小明买了一张火车票
    小明买了一张电影票

    Jenic

    856***[email protected]

    5年前 (2021年03月10日)
  4. #0

    夜夜

    132***[email protected]

    15

    实例化委托:

    using System;
    delegate int NumberChanger(int n);
    namespace Appliction{
     class TestDelegate{
     static int num=10;
     public static int Add(int n){
     num+=n;
     return num;
     }
     
     public static int Mult(int n){
     num*=n;
     return num;
     }
     
     public static int GetNum(){
     return num;
     }
     
     
     static void Main(string[] args){
     NumberChanger a1=new NumberChanger(Add);
     NumberChanger a2=new NumberChanger(Mult);
     a1(5);
     Console.WriteLine("进行加法后的结果为:{0}",GetNum());
     a2(10);
     Console.WriteLine("进行乘法后的结果位:{0}",GetNum());
     Console.ReadLine();
     
     }
     }
    }

    委托的多播

    nc=n1+n2;

    体现了多个委托能够串行运行,这里的 + 号被重载了。

    using System;
    delegate int NumberChanger(int n);
    namespace DelegateAppl
    {
     class TestDelegate
     {
     static int num = 10;
     public static int AddNum(int p)
     {
     num += p;
     return num;
     }
     public static int MultNum(int q)
     {
     num *= q;
     return num;
     }
     public static int getNum()
     {
     return num;
     }
     static void Main(string[] args)
     {
     // 创建委托实例
     NumberChanger nc;
     NumberChanger nc1 = new NumberChanger(AddNum);
     NumberChanger nc2 = new NumberChanger(MultNum);
     // 使用委托对象调用方法
     nc=nc1+nc2;
     nc1(25);
     Console.WriteLine("Value of Num: {0}", getNum());
     nc2(5);
     Console.WriteLine("Value of Num: {0}", getNum());
     nc(5);
     Console.WriteLine("Vlue of Num: {0}",getNum());
     Console.ReadKey();
     }
     }
    }

    夜夜

    132***[email protected]

    5年前 (2021年09月15日)

点我分享笔记

  • 昵称 (必填)
  • 邮箱 (必填)
  • 引用地址

AltStyle によって変換されたページ (->オリジナル) /