匿名函数、委托、lambda表达式、扩展方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 匿名函数与lambda
{
class Program
{
static void Main(string[] args)
{
//委托调用方法
someDelegate1 sv = new someDelegate1(SayHello);
//匿名函数 只能在委托中使用
//语法 委托对象=delegate(参数列表){表达式};
someDelegate f = delegate(string s)
{
Console.WriteLine("匿名函数:hello," + s);
};
f("zhangfeng");
//lambda表达式,简化操作,初看很恐怖,多用于和linq混合使用
someDelegate f1 = (s1) =>
{
Console.WriteLine("lambda表达式:hi,"+s1);
};
f1("lambda");
//lambda表达式+linq示例
int[] values = { 3, 6, 9, -7, 32 };
foreach (int i in values.Select(i => i * 2))
{
Console.WriteLine(i);
}
//扩展方法 .net 3.5版本新加的,早期版本用不了,linq是用扩展方法实现的
string str1 = "abc@qq.com";
//扩展方法的调用,调用扩展方法,第一个参数 其实是.前面的对象
Console.WriteLine(str1.IsEmail());
//跟扩展方法比较,普通调用
Console.WriteLine(StringHelper.IsEmail(str1));
//扩展方法重载,第二个参数照实写
Console.WriteLine(str1.IsEmail("sv"));
Console.Read();
}
static string SayHello()
{
return "h1";
}
}
//实现扩展方法,定义类前面要加static
static class StringHelper
{
//方法前面要加static(静态类中方法必须加static),参数变量加this,第一个参数为待扩展的类型,调用他的类型必须与第一个参数类型相同
public static bool IsEmail(this string s)
{
if(s.Contains("@"))
{
return true;
}
return false;
}
public static bool IsEmail(this string s,string v)
{
if (s.Contains("@"))
{
return true;
}
return false;
}
}
delegate void someDelegate(string s);
delegate string someDelegate1();
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 匿名函数与lambda
{
class Program
{
static void Main(string[] args)
{
//委托调用方法
someDelegate1 sv = new someDelegate1(SayHello);
//匿名函数 只能在委托中使用
//语法 委托对象=delegate(参数列表){表达式};
someDelegate f = delegate(string s)
{
Console.WriteLine("匿名函数:hello," + s);
};
f("zhangfeng");
//lambda表达式,简化操作,初看很恐怖,多用于和linq混合使用
someDelegate f1 = (s1) =>
{
Console.WriteLine("lambda表达式:hi,"+s1);
};
f1("lambda");
//lambda表达式+linq示例
int[] values = { 3, 6, 9, -7, 32 };
foreach (int i in values.Select(i => i * 2))
{
Console.WriteLine(i);
}
//扩展方法 .net 3.5版本新加的,早期版本用不了,linq是用扩展方法实现的
string str1 = "abc@qq.com";
//扩展方法的调用,调用扩展方法,第一个参数 其实是.前面的对象
Console.WriteLine(str1.IsEmail());
//跟扩展方法比较,普通调用
Console.WriteLine(StringHelper.IsEmail(str1));
//扩展方法重载,第二个参数照实写
Console.WriteLine(str1.IsEmail("sv"));
Console.Read();
}
static string SayHello()
{
return "h1";
}
}
//实现扩展方法,定义类前面要加static
static class StringHelper
{
//方法前面要加static(静态类中方法必须加static),参数变量加this,第一个参数为待扩展的类型,调用他的类型必须与第一个参数类型相同
public static bool IsEmail(this string s)
{
if(s.Contains("@"))
{
return true;
}
return false;
}
public static bool IsEmail(this string s,string v)
{
if (s.Contains("@"))
{
return true;
}
return false;
}
}
delegate void someDelegate(string s);
delegate string someDelegate1();
}