一个简单的Delegate使用例子
2017-02-10 13:45
531 查看
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace delegateDemo
{
class Program
{
static void OtherClassMethod()
{
Console.WriteLine("another class's static method");
}
static void Main(string[] args)
{
var test = new TestDelegate();
test.delegateMethod = new TestDelegate.DelegateMethod(test.NonStaticMethod);
test.delegateMethod += new TestDelegate.DelegateMethod(TestDelegate.StaticMethod);
test.delegateMethod += Program.OtherClassMethod;
test.RunDelegateMethods();
}
}
class TestDelegate
{
public delegate void DelegateMethod(); //声明了一个Delegate Type
public DelegateMethod delegateMethod; //声明了一个Delegate对象
public static void StaticMethod()
{
Console.WriteLine("Delegate a static method");
}
public void NonStaticMethod()
{
Console.WriteLine("Delegate a non-static method");
}
public void RunDelegateMethods()
{
if (delegateMethod != null)
{
Console.WriteLine("---------");
delegateMethod.Invoke();
Console.WriteLine("---------");
}
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace delegateDemo
{
class Program
{
static void OtherClassMethod()
{
Console.WriteLine("another class's static method");
}
static void Main(string[] args)
{
var test = new TestDelegate();
test.delegateMethod = new TestDelegate.DelegateMethod(test.NonStaticMethod);
test.delegateMethod += new TestDelegate.DelegateMethod(TestDelegate.StaticMethod);
test.delegateMethod += Program.OtherClassMethod;
test.RunDelegateMethods();
}
}
class TestDelegate
{
public delegate void DelegateMethod(); //声明了一个Delegate Type
public DelegateMethod delegateMethod; //声明了一个Delegate对象
public static void StaticMethod()
{
Console.WriteLine("Delegate a static method");
}
public void NonStaticMethod()
{
Console.WriteLine("Delegate a non-static method");
}
public void RunDelegateMethods()
{
if (delegateMethod != null)
{
Console.WriteLine("---------");
delegateMethod.Invoke();
Console.WriteLine("---------");
}
}
}
}
相关文章推荐
- GDB 7.0 中文手册 —— 1. GDB简介和一个简单的使用例子
- Canlendar类使用的一个简单例子
- 使用servlet开发动态wap的一个简单例子
- 一个简单的HTTP通讯的例子,使用了CInternetSession,CHttpConnection,CHttpFile三个类。
- 词法分析程序 LEX和VC6整合使用的一个简单例子
- 在MFC下使用OpenGL的一个简单的例子
- web.config文件自定义配置节的使用方法的一个简单例子
- 通过编码方式使用性能计数器来进行性能计数的一个简单例子 - ZT
- 一个简单的使用XMLHttpRequest获得服务器数据的例子
- 一是最简单的例子让你学会如何使用XML来做一个页面
- Linux下,使用C/C++编写"静态链接库"的一个简单例子
- 一个使用多媒体定时器的简单例子
- Canlendar类使用的一个简单例子
- 一个C#中使用 event 和 delegate的小例子。
- 通过一个简单的例子,介绍如何使用LDAP(转)
- 委托delegate的学习.+一个简单的委托和委托链的例子
- 一个使用spring的最简单的例子。
- web.config文件自定义配置节的使用方法的一个简单例子
- 在MFC下使用OpenGL的一个简单的例子(基于单文档程序)
- 使用 Equinox 的Declarative Service 的一个简单例子