C#基础学习之委托
委托(delegate)
委托属于引用类型,用于封装方法(函数)的引用。它类似于C++中的函数指针,但有所不同,委托是完全面向对象的,是类型安全和可靠的;另外,C++指针仅指向成员函数,而委托同时封装了对象实例和方法。
使用委托包含几个步骤:委托声明、委托实例化和委托调用
1、委托声明
委托声明用于定义一个从System.Delegate类派生的类,其格式为:
属性集 修饰符 delegate 返回值类型 标识符(形参列表);
其中,修饰符可为public、protected、internal、private和new
2、委托实例化
委托实例化用于创建委托实例化,与类实例创建的语法相同,委托实例可以封装多个,
方法,该方法的集合称为调用列表,委托使用“+”,“+=”,“-”,“-=”运算符向调用列表中增加或移除方法。
3、委托调用例子
View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Delegate
{
delegate void TimeDelegate(string s); //委托声明
//新建一个类
public class MyTime
{
public static void HelloTime(string s)
{
Console.WriteLine("Hello {0}!The time is {1} now", s, DateTime.Now);
}
public static void GoodbyeTime(string s)
{
Console.WriteLine("Goodbye {0}!The time is {1} now", s, DateTime.Now);
}
public void SayHello(string s)
{
Console.WriteLine("{0}!The time is {1} now", s, DateTime.Now);
}
}
class Program
{
static void Main(string[] args)
{
//委托实例化,创建委托实例a,并封装静态方法
TimeDelegate a = new TimeDelegate(MyTime.HelloTime);
Console.WriteLine("Invoking delegate a: ");
//委托调用,相当于调用方法MyTime.HelloTime("A")
a("A");
TimeDelegate b = new TimeDelegate(MyTime.GoodbyeTime);
Console.WriteLine("Invoking delegate b: ");
b("B");
//委托实例c封装了两个方法HelloTime和GoodbyeTime
TimeDelegate c = a + b;
Console.WriteLine("Invoking delegate c: ");
c("C");
c -= a;
Console.WriteLine("Invoking delegate c: ");
c("C");
MyTime time = new MyTime();
TimeDelegate d = new TimeDelegate(time.SayHello);
Console.WriteLine("Invoking delegate d: ");
d("D");
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Delegate
{
delegate void TimeDelegate(string s); //委托声明
//新建一个类
public class MyTime
{
public static void HelloTime(string s)
{
Console.WriteLine("Hello {0}!The time is {1} now", s, DateTime.Now);
}
public static void GoodbyeTime(string s)
{
Console.WriteLine("Goodbye {0}!The time is {1} now", s, DateTime.Now);
}
public void SayHello(string s)
{
Console.WriteLine("{0}!The time is {1} now", s, DateTime.Now);
}
}
class Program
{
static void Main(string[] args)
{
//委托实例化,创建委托实例a,并封装静态方法
TimeDelegate a = new TimeDelegate(MyTime.HelloTime);
Console.WriteLine("Invoking delegate a: ");
//委托调用,相当于调用方法MyTime.HelloTime("A")
a("A");
TimeDelegate b = new TimeDelegate(MyTime.GoodbyeTime);
Console.WriteLine("Invoking delegate b: ");
b("B");
//委托实例c封装了两个方法HelloTime和GoodbyeTime
TimeDelegate c = a + b;
Console.WriteLine("Invoking delegate c: ");
c("C");
c -= a;
Console.WriteLine("Invoking delegate c: ");
c("C");
MyTime time = new MyTime();
TimeDelegate d = new TimeDelegate(time.SayHello);
Console.WriteLine("Invoking delegate d: ");
d("D");
}
}