标签:
#region 9-1用匿名方法来创建委托实例
Func<string, int> returnLength;//等价public delegate int SomeDelegate(string arg1)。当返回void时,使用Action<>系列委托
returnLength = delegate(string text) { return text.Length; };
Console.WriteLine(returnLength("Holle"));
#endregion
#region 9-2冗长的第一个Lambda表达式
Func<string, int> returnLength;
returnLength = (string text) => { return text.Length; };
returnLength = (string text) => text.Length;//用单一表达式做为主体
returnLength = (text) => text.Length;//隐式类型的参数列表
returnLength = text => text.Length;//单一参数的快捷语法
Console.WriteLine(returnLength("Holle"));
#endregion
#region 9-4用Lambda处理一个电影列表
var films = new List<Film>
{
new Film{Name="Jaws1",Year=1975},
new Film{Name="Jaws2",Year=1975},
new Film{Name="Jaws5",Year=1975},
new Film{Name="Jaws4",Year=1976},
};
Action<Film> print = film => Console.WriteLine("Name={0},Year={1}", film.Name, film.Year);
films.ForEach(print);//打印全部元素
films.FindAll(film => film.Year > 1975).ForEach(print);//过滤打印
films.Sort((f1, f2) => f1.Name.CompareTo(f2.Name));//排序打印
films.ForEach(print);
#endregion
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Button button = new Button { Text = "Click me" };
button.Click += (src, e) => Log("Click", src, e);
button.KeyPress += (src, e) => Log("KeyPress", src, e);
button.MouseClick+=(src,e)=>Log("MouseClick",src,e);
Form form = new Form { AutoSize = true, Controls = { button } };
Application.Run(form);
}
static void Log(string title, object sender, EventArgs e)
{
Console.WriteLine("Event:{0}", title);
Console.WriteLine("Sender:{0}", sender);
Console.WriteLine("Argument:{0}", e);
foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(e))
{
string name = prop.DisplayName;
object value = prop.GetValue(e);
Console.WriteLine(" {0}={1}", name, value);
}
}
static void Log(string title, object sender)
{
Console.WriteLine("Event:{0}", title);
Console.WriteLine("Sender:{0}", sender);
}
}
#region 9-6一个非常简单的表达式树
//System.Linq.Expressions命名空间包含了代表表达式的各个类,他们都继承至Expression
Expression firstArg = Expression.Constant(2);
Expression secondArg = Expression.Constant(3);
Expression add = Expression.Add(firstArg, secondArg);
Console.WriteLine(add);
#endregion
#region 9-7编译并执行一个表达式
Expression firstArg = Expression.Constant(2);
Expression secondArg = Expression.Constant(3);
Expression add = Expression.Add(firstArg, secondArg);
Func<int> compiled = Expression.Lambda<Func<int>>(add).Compile();
Console.WriteLine(compiled());
#endregion
#region 9-8用Lambda表达式转换成表达式树
Expression<Func<int>> return5 = () => 5;//Lambda表达式
Func<int> compiled1 = return5.Compile();
Console.WriteLine(compiled1());
#endregion
#region 9-9演示一个更复杂的表达式树
Expression<Func<string, string, bool>> expression = (x, y) => x.StartsWith(y);
var compiled = expression.Compile();
Console.WriteLine(compiled("First", "Second"));
Console.WriteLine(compiled("First", "Fir"));
#endregion
#region 9-10用代码来构造一个方法调用表达式树
MethodInfo method = typeof(string).GetMethod("StartsWith", new[] { typeof(string) });//获取方法名为StartsWith,参数为string的公共方法
var target = Expression.Parameter(typeof(string), "x");
var methodArg = Expression.Parameter(typeof(string), "y");
Expression[] methodArgs = new[] { methodArg };
//Call(Expression instance, MethodInfo method, params Expression[] arguments)
Expression call = Expression.Call(target, method, methodArgs);//x.StartsWith(y),以上部件创建CallExpression
var lambdaParameters = new[] { target, methodArg };//这里使用的参数顺序就是调用委托所使用的参数顺序
var lambda = Expression.Lambda<Func<string, string, bool>>(call, lambdaParameters);//(x,y)=>x.StartsWith(y),lambdaParameters填充call集合
var compiled = lambda.Compile();//生成lambda表达式的委托
Console.WriteLine(compiled("First", "csend"));
Console.WriteLine(compiled("First", "Fir"));
#endregion
#region 9-11 需要新的类型推断规则例子(用Lambda表达式调用一个泛型方法)
static void PrintConvertedValue<TInput, TOutput>(TInput input, Converter<TInput, TOutput> converter)
{
Console.WriteLine(converter(input));
}
#endregion
#region 9-11
PrintConvertedValue("I‘m a string", x => x.Length);//C#2中,编译将失败,C#2类型推断单独针对每一个实参来进行的,从一个实参无法推断出另一个实参
#endregion
#region 9-13根据一天当中的时间来选择返回int或object
delegate T MyFunc<T>();
static void WriteResult<T>(MyFunc<T> function)
{
Console.WriteLine(function());
}
#endregion
#region 9-13
WriteResult(delegate
{
if (DateTime.Now.Hour < 22)//int
{
return 10;
}
else//object
{
return new object();
}
});//编译器采用处理隐式数组的逻辑处理返回类型,对int进行了装箱,返回类型为object
#endregion
#region 9-14综合来自多个实参的信息,灵活地进行类型推断
static void PrintType<T>(T first, T second)//被强制转换为具体类型参数的最终固定变量类型
{
Console.WriteLine(typeof(T));
}
#endregion
#region 9-14
PrintType(1,new object());//返回类型推断为object类型
#endregion
#region 9-15多级类型推断
static void ConvertTwice<TInput, TMiddle, TOutput>(TInput input, Converter<TInput, TMiddle> firstConversion, Converter<TMiddle, TOutput> secondConversion)
{
TMiddle middle = firstConversion(input);
TOutput output = secondConversion(middle);
Console.WriteLine(output);
}
#endregion
#region 9-15
//第一阶段,编译器处理普通实参,得到TInput类型string,第一次执行阶段二,TInput固定为string类型,推断TMiddle为int,再次执行第二阶段,TMiddle固定为int,TOutput为double,推断结束
//lambda表达式主体只有在输入参数的类型已知后才能进行检查
ConvertTwice("Another string", text => text.Length, length => Math.Sqrt(length));
#endregion
#region 9-16委托返回类型影响了重载选择
//如果一个匿名函数能转换成参数列表相同,但返回类型不同的两个委托类型,就根据从“推断的返回类型”到“委托的返回类型”的转换来判断哪个委托转换好
static void Execute(Func<int> action)
{
Console.WriteLine("action return an int:" + action());
}
static void Execute(Func<double> action)
{
Console.WriteLine("action return a douban:" + action());
}
#endregion
#region 9-16
Execute(() => 1);
#endregion
标签:
原文地址:http://www.cnblogs.com/Tan-sir/p/5169217.html