突然寫這篇文章
首先我想說說有關事件
那麼我舉幾個有關事件的例子
代理:(有的書上也翻譯成指代或委托
我想很多剛接觸C#的人
舉個例子:
public delegate void GetString()//我申明了一個代理
現在我要用到它了如下;
int i=
GetString gs=new GetString(i
如下:
float j=
GetString gs=new GetString(j
可是
事實上
Single Delegate:(單路代理)
從字面上
public delegate bool Myfun(string str
現在我再來寫一個方法如下:
bool CompareStrToInt(string s
{
if(s
return true;
else
return false;
}
這個方法完成的工作很簡單對吧
Myfun mf=new (CompareStrToInt);
string s=
int i=
ConSole
輸出結果:
Value=true
這就是單路代理
多路廣播:
一個代理同時代理幾個方法
using System;
namespace Multi_castDelegate
{
/// <summary>
/// Summary description for Class
/// </summary>
class MyClassDelegate
{
/// <summary>
/// The main entry point for the application
/// </summary>
public delegate string IntDelegate(string s);
}
}
using System;
namespace Multi_castDelegate
{
/// <summary>
/// Summary description for MyImplementingClass
/// </summary>
public class MyClass
{
public MyClass()
{
}
public static string WriteString(string s)
{
Console
return
}
public static string logString(string s)
{
Console
return
}
public static string TransmitString(string s)
{
Console
return
}
}
}
The Main class:
using System;
using System
namespace Multi_castDelegate
{
/// <summary>
/// Summary description for Test
/// </summary>
public class Test
{
public static void Main()
{
MyClassDelegate
Writer
MyClassDelegate
myDelegate;
Writer=new
MyClassDelegate
/// calling Writer
Writer(
Logger=new MyClassDelegate
///calling Logger
Logger(
Transmitter=new MyClassDelegate
///calling Transmitter
Transmitter(
///here mydelegate used the Combine method of System
///and the delegates combine
myDelegate=(MyClassDelegate
myDelegate(
///here Transmitter is also added using the overloaded form of Combine
myDelegate+=Transmitter;
myDelegate(
///now using the Remove method
myDelegate=(MyClassDelegate
myDelegate(
///overloaded Remove
myDelegate
myDelegate(
System
}
}
}
(上面的例子是在一個國外網站上找到的
上面的例子重點是看那兩個已經重載的操作符
From:http://tw.wingwit.com/Article/program/net/201311/11741.html