using
System;
namespace Add
{
delegate void numberAdd( int a, int b);
class program
{
static void ADD0( int a, int b)
{
Console.WriteLine(a + b);
}
static void Main()
{
numberAdd n1 = ADD0;
int x;
int y;
x = int.Parse(Console.ReadLine());
y = int.Parse(Console.ReadLine());
n1(x, y);
Console.ReadLine();
}
}
}
namespace Add
{
delegate void numberAdd( int a, int b);
class program
{
static void ADD0( int a, int b)
{
Console.WriteLine(a + b);
}
static void Main()
{
numberAdd n1 = ADD0;
int x;
int y;
x = int.Parse(Console.ReadLine());
y = int.Parse(Console.ReadLine());
n1(x, y);
Console.ReadLine();
}
}
}
[/code]
偶又用匿名方法优化了下代码,这样就简洁多了
[code]
using
System;
namespace Add
{
delegate void numberAdd( int a, int b);
class program
{
static void Main()
{
numberAdd n1 = delegate( int a, int b)
{
Console.WriteLine(a + b);
};
int x = int.Parse(Console.ReadLine());
int y = int.Parse(Console.ReadLine());
n1(x, y);
Console.ReadLine();
}
}
}
namespace Add
{
delegate void numberAdd( int a, int b);
class program
{
static void Main()
{
numberAdd n1 = delegate( int a, int b)
{
Console.WriteLine(a + b);
};
int x = int.Parse(Console.ReadLine());
int y = int.Parse(Console.ReadLine());
n1(x, y);
Console.ReadLine();
}
}
}
本文展示了如何在C#中使用委托和匿名方法实现两个整数的加法运算。通过定义委托类型并使用静态方法及匿名方法进行实例化,实现了灵活的函数传递和调用。
889

被折叠的 条评论
为什么被折叠?



