1:
//直接上MSDN上的C#代码:
using System;
public class SamplesDelegate
{
// Declares a delegate for a method that takes in an int and returns a String.
public delegate String myMethodDelegate(int myInt);
// Defines some methods to which the delegate can point.
public class mySampleClass
{
// Defines an instance method.
public String myStringMethod(int myInt)
{
if (myInt > 0)
return ("positive");
if (myInt < 0)
return ("negative");
return ("zero");
}
// Defines a static method.
public static String mySignMethod(int myInt)
{
if (myInt > 0)
return ("+");
if (myInt < 0)
return ("-");
return ("");
}
}
public static void Main()
{
// Creates one delegate for each method. For the instance method, an
// instance (mySC) must be supplied. For the static method, use the
// class name.
mySampleClass mySC = new mySampleClass();
myMethodDelegate myD1 = new myMethodDelegate(mySC.myStringMethod);
myMethodDelegate myD2 = new myMethodDelegate(mySampleClass.mySignMethod);
// Invokes the delegates.
Console.WriteLine("{0} is {1}; use the sign \"{2}\".", 5, myD1(5), myD2(5));
Console.WriteLine("{0} is {1}; use the sign \"{2}\".", -3, myD1(-3), myD2(-3));
Console.WriteLine("{0} is {1}; use the sign \"{2}\".", 0, myD1(0), myD2(0));
}
}
2:
// d11.cpp : Defines the entry point for the console application.
//C++代码
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
typedef string myMethodDelegate(int myInt);
string myStringMethod ( int myInt ) {
if ( myInt > 0 )
return string( "positive" );
if ( myInt < 0 )
return string( "negative" );
return string( "zero" );
}
string mySignMethod ( int myInt ) {
if ( myInt > 0 )
return string( "+" );
if ( myInt < 0 )
return string( "-" );
return string( "" );
}
int _tmain(int argc, _TCHAR* argv[])
{
myMethodDelegate* myD1 = myStringMethod;
myMethodDelegate* myD2 = mySignMethod;
// Invokes the delegates.
printf( "{%d} is {%s}; use the sign \"{%s}\". \r\n", 5, myD1( 5 ).c_str(), myD2( 5 ).c_str() );
printf( "{%d} is {%s}; use the sign \"{%s}\". \r\n", -3, myD1( -3 ).c_str(), myD2( -3 ).c_str() );
printf( "{%d} is {%s}; use the sign \"{%s}\".\r\n", 0, myD1( 0 ).c_str(), myD2( 0 ).c_str() );
return 0;
}