Tuesday, August 24, 2010

Recall the Use of Delegate

1.Define delegate use function signature:

ex.

delegate string MyDelegate(int i);

public static vod Main(args[])
{
MyDelegate d=myFunc;
Console.WriteLine(d(5));
}
static string MyFunc(int a)
{
return a.ToString();
}

2. Use delegate to call back a function,
change the code MyDelegate d=myFunc to MyDelegate d=new MyDelegate(myFunc);

The code will be:

delegate string MyDelegate(int i);

public static vod Main(args[])
{
MyDelegate d=new MyDelegate(myFunc);
Console.WriteLine(d(5));
}
static string MyFunc(int a)
{
return a.ToString();
}

3. Multicast delegate:

delegate void MyDelegate(int i);

public static vod Main(args[])
{
MyDelegate d=(MyDelegate)myFunc1+(MyDelegate)myFunc2-(MyDelegate)myFunc1;
d(5);
}
static void MyFunc1(int a)
{
Console.WriteLine(a.ToString());
}
static string MyFunc2(int a)
{
Console.WriteLine("second function:"+a.ToString());
}

4. Delegate Chain:

delegate void MyDelegate(int i);

public static vod Main(args[])
{
MyDelegate[] ds= new MyDelegate[]{(MyDelegate)myFunc1,(MyDelegate)myFunc2};
MyDelegate d=(MyDelegate)Delegate.Combine(ds);
d(5);
}
static void MyFunc1(int a)
{
Console.WriteLine(a.ToString());
}
static string MyFunc2(int a)
{
Console.WriteLine("second function:"+a.ToString());
}

5. delegate call anonymous method:

delegate void MyDelegate(int myint);

static void Main(args[])
{
MyDelegate d=delegate(int i){Console.WriteLine(i.ToString());}
d(5);
}

delegate to call anonymous method can be represented as lambda expression, so we can also write the above code as:

delegate void MyDelegate(int myint);

static void Main(args[])
{
MyDelegate d=(int i)=>{Console.WriteLine(i.ToString());};
d(5);
}

No comments: