C#中的委托样例代码
C#中的委托样例代码(一)
using System;
namespace Wrox.ProCSharp.AdvancedCSharp
{
delegate double DoubleOp(double x);
class MainEntryPoint
{
static void Main()
{
DoubleOp[] operations =
{
new DoubleOp(MathsOperations.MultiplyByTwo),
new DoubleOp(MathsOperations.Square)
};
for (int i = 0; i < operations.Length; i++)
{
Console.WriteLine("Using operations[{0}]:", i);
ProcessAndDisplayNumber(operations[i], 2.0);
ProcessAndDisplayNumber(operations[i], 7.94);
ProcessAndDisplayNumber(operations[i], 1.414);
Console.WriteLine();
}
}
static void ProcessAndDisplayNumber(DoubleOp action, double value)
{
double result = action(value);
Console.WriteLine("Value is {0}, result of operation is {1}", value, result);
}
}
class MathsOperations
{
public static double MultiplyByTwo(double value)
{
return value * 2;
}
public static double Square(double value)
{
return value * value;
}
}
}
C#中的委托样例代码(二)
Posted on 2004-06-04 14:17 集思 阅读(505)
using System;
namespace Wrox.ProCSharp.AdvancedCSharp
{
delegate void DoubleOp(double value);
class MainEntryPoint
{
static void Main()
{
DoubleOp operations = new DoubleOp(MathsOperations.MultiplyByTwo);
operations += new DoubleOp(MathsOperations.Square);
ProcessAndDisplayNumber(operations, 2.0);
ProcessAndDisplayNumber(operations, 7.94);
ProcessAndDisplayNumber(operations, 1.414);
Console.WriteLine();
}
static void ProcessAndDisplayNumber(DoubleOp action, double value)
{
Console.WriteLine(" ProcessAndDisplayNumber called with value = " + value);
action(value);
}
}
class MathsOperations
{
public static void MultiplyByTwo(double value)
{
double result = value*2;
Console.WriteLine("Multiplying by 2: {0} gives {1}", value, result);
}
public static void Square(double value)
{
double result = value*value;
Console.WriteLine("Squaring: {0} gives {1}", value, result);
}
}
}