110,010
社区成员




using System;
using System.Collections.Generic;
using System.Text;
namespace Delegate_01
{ //the delegate defined here has none arguments
class Currency
{
public uint Dollars;
public ushort Cents;
/// <summary>
/// constructor function
/// </summary>
/// <param name="dollars"></param>
/// <param name="cents"></param>
public Currency(uint dollars, ushort cents)
{
if (cents >99)
{
dollars += (uint)(cents / 100);
cents = (ushort)(cents % 100);
}
this.Dollars = dollars;
this.Cents = cents;
}
/// <summary>
/// override ToString() function
/// </summary>
/// <returns></returns>
public override string ToString()
{
return string.Format("{0} Dollars {1} Cents", this.Dollars, this.Cents);
}
/// <summary>
/// add a static function with the same signature as Currency
/// </summary>
/// <returns></returns>
public static string GetCurrencyUnit()
{
return "Cognizant.com";
}
}
class Program
{
// define a delegate with none arguments
private delegate string GetAString();
static void Main(string[] args)
{
int x = 100;
GetAString astr = new GetAString(x.ToString); // int.ToString();
Console.WriteLine("x string is \"{0}\"", astr());
Currency balance = new Currency(13,153);
astr = new GetAString(balance.ToString); // the parameter should be the method's name only
// the ToString() function here was override in the class Currency
Console.WriteLine("balabce string is \"{0}\"", astr ());
astr = new GetAString(Currency.GetCurrencyUnit); // the parameter should be the method's name only
Console.WriteLine("GetAString : \"{0}\"", astr());
Console.ReadKey();
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication7
{
class Program
{
public delegate void Del(string ss);
public static void Show(string ss)
{
Console.WriteLine(ss);
}
public static void ShowLZ(string ss)
{
Console.WriteLine("楼主,{0}", ss);
}
static void Main(string[] args)
{
Del del1 = Show;
del1("其实我的真正身份是Show,是del1装B装的");
Del del2 = ShowLZ;
del2("给分给我啊");
Console.ReadKey();
}
}
}
using System;
public delegate void Del(string ss);
public class A1
{
public Del StringDeleted;
public DeleteString()
{
if( StringDeleted != null )
{
StringDeleted("Someone has deleted my string");
}
}
}
public class Program
{
static void Main()
{
A1 a = new A1();
a.DeleteString();
Console.ReadLine();
a.StringDeleted = OnStringDelete; //<--- 传递一个函数,以便得到通知。
a.DeleteString(); //Log: Someone has deleted my string
Console.ReadLine();
}
static void OnStringDelete(string ss)
{
Console.WriteLine("Log: " + ss );
}
}