匿名方法:
方法只用一次,就可以采用匿名函数的方式。
无参数无返回值的匿名函数:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 接口
{
class Program
{
static void Main(string[] args)
{
//匿名方法
//匿名方法不能直接在类中定义。而是在给委托变量赋值的时候,需要赋值一个方法,此时可以“现做现卖”,定义一个匿名方法传递给委托。
MyDelegate md = delegate() {
Console.WriteLine("匿名函数");
};
md.Invoke();
Console.ReadKey();
}
}
public delegate void MyDelegate();
}
有参数无返回值的匿名函数:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 接口
{
class Program
{
static void Main(string[] args)
{
//匿名方法
//匿名方法不能直接在类中定义。而是在给委托变量赋值的时候,需要赋值一个方法,此时可以“现做现卖”,定义一个匿名方法传递给委托。
Mydelegate1 md = delegate(string txt)
{
Console.WriteLine("早"+txt);
};
md.Invoke("大家好");
Console.ReadKey();
}
}
public delegate void MyDelegate();
public delegate void Mydelegate1(string val);
}
有参数有返回值的匿名函数:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 接口
{
class Program
{
static void Main(string[] args)
{
//匿名方法
//匿名方法不能直接在类中定义。而是在给委托变量赋值的时候,需要赋值一个方法,此时可以“现做现卖”,定义一个匿名方法传递给委托。
Mydelegate2 md = delegate(int n1,int n2,int n3)
{
return n1 + n2 + n3;
};
int n4=md.Invoke(1,2,3);
Console.WriteLine(n4);
Console.ReadKey();
}
}
public delegate void MyDelegate();
public delegate void Mydelegate1(string val);
public delegate int Mydelegate2(int n1,int n2,int n3);
}