Download presentation
Presentation is loading. Please wait.
1
Advanced .NET Programming I 13th Lecture
Pavel Ježek Some of the slides are based on University of Linz .NET presentations. © University of Linz, Institute for System Software, 2004 published under the Microsoft Curriculum License (
2
Lambda Expressions (připomenutí ze ZS)
Example of C# 2.0 anonymous method: class Program { delegate T BinaryOp<T>(T x, T y); static void Method<T>(BinaryOp<T> op, T p1, T p2) { Console.WriteLine(op(p1, p2)); } static void Main() { Method(delegate(int a, int b) { return a + b; }, 1, 2); C# 3.0 lambda expressions provide further simplification: Method((a, b) => a + b, 1, 2);
3
Lambda Expressions (2) (připomenutí ze ZS)
Expression or statement body Implicitly or explicitly typed parameters Examples: x => x // Implicitly typed, expression body x => { return x + 1; } // Implicitly typed, statement body (int x) => x // Explicitly typed, expression body (int x) => { return x + 1; } // Explicitly typed, statement body (x, y) => x * y // Multiple parameters () => Console.WriteLine() // No parameters A lambda expression is a value, that does not have a type but can be implicitly converted to a compatible delegate type delegate R Func<A,R>(A arg); Func<int,int> f1 = x => x + 1; // Ok Func<int,double> f2 = x => x + 1; // Ok Func<double,int> f3 = x => x + 1; // Error – double cannot be // implicitly converted to int
4
Lambda Expressions (3) (připomenutí ze ZS)
Lambda expressions participate in inference process of type arguments of generic methods In initial phase, nothing is inferred from arguments that are lambda expressions Following the initial phase, additional inferences are made from lambda expressions using an iterative process
5
Lambda Expressions (4) (připomenutí ze ZS)
Generic extension method example: public class List<T> : IEnumerable<T>, … { … } public static class Sequence { public static IEnumerable<S> Select<T,S>( this IEnumerable<T> source, Func<T, S> selector) { foreach (T element in source) yield return selector(element); } Calling extension method with lambda expression: List<Customer> customers = GetCustomerList(); IEnumerable<string> names = customers.Select(c => c.Name); Rewriting extension method call: IEnumerable<string> names = Sequence.Select<T, S>(customers, c => c.Name); T type argument is inferred to Customer based on source argument type Sequence.Select<Customer, S>(customers, c => c.Name) c lambda expression argument type is infered to Customer Sequence.Select<Customer, S>(customers, (Customer c) => c.Name) S type argument is inferred to string based on return value type of the lambda expression Sequence.Select<Customer, string>(customers, (Customer c) => c.Name)
6
Lambda Expressions as Delegates (připomenutí ze ZS – nový slide)
When assigned to a delegate, equivalent code of an anonymous method is generated at compile time! value => (value + 2) * 10 Func<int, int> f = Compile time generation IL_0000: ldarg.0 IL_0001: ldc.i4.2 IL_0002: add IL_0003: ldc.i4.s 10 IL_0005: mul IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret
7
Lambda Expressions as Expression Trees
Permit lambda expressions to be represented as data structures instead of executable code Lambda expression convertible to delegate D (assignment causes code generation) is also convertible to expression tree (abstract syntax tree) of type System.Linq.Expressions.Expression<D> (assignment causes expression tree generation – compile time generation of code, that creates the expression tree [class instances] at runtime) Expression trees are immutable value => (value + 2) * 10 Func<int, int> f = Expression<Func<int, int>> e = Compile time generation Compile time generation IL_0000: ldarg.0 IL_0001: ldc.i4.2 IL_0002: add IL_0003: ldc.i4.s 10 IL_0005: mul IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret new LambdaExpression( new BinaryExpression( ParameterExpression(“value”) ConstantExpression(2) ) ConstantExpression(10)
8
Expression Trees and LINQ
9
Expression Trees Classes inheriting from Expression (since .NET 3.5):
System.Linq.Expressions.BinaryExpression System.Linq.Expressions.ConditionalExpression System.Linq.Expressions.ConstantExpression System.Linq.Expressions.InvocationExpression System.Linq.Expressions.LambdaExpression System.Linq.Expressions.MemberExpression System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.NewExpression System.Linq.Expressions.NewArrayExpression System.Linq.Expressions.MemberInitExpression System.Linq.Expressions.ListInitExpression System.Linq.Expressions.ParameterExpression System.Linq.Expressions.TypeBinaryExpression System.Linq.Expressions.UnaryExpression New classes inheriting from Expression (since .NET 4.0): System.Linq.Expressions.BlockExpression System.Linq.Expressions.LoopExpression System.Linq.Expressions.TryExpression …
10
Lambda Expressions as Expression Trees
value => (value + 2) * 10 Func<int, int> f = Expression<Func<int, int>> e = Compile time generation Compile time generation IL_0000: ldarg.0 IL_0001: ldc.i4.2 IL_0002: add IL_0003: ldc.i4.s 10 IL_0005: mul IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret new LambdaExpression( new BinaryExpression( ParameterExpression(“value”) ConstantExpression(2) ) ConstantExpression(10) Runtime time generation by JIT machine code (e.g. x86) (code actually executed by real CPU)
11
Expression Trees to Dynamic Methods (via Implicit Reflection.Emit)
Runtime generation of CIL code of a dynamic method from expression tree instance: value => (value + 2) * 10 Func<int, int> f = Expression<Func<int, int>> e = Compile time generation Compile time generation IL_0000: ldarg.0 IL_0001: ldc.i4.2 IL_0002: add IL_0003: ldc.i4.s 10 IL_0005: mul IL_0006: stloc.0 IL_0007: br.s IL_0009 IL_0009: ldloc.0 IL_000a: ret new LambdaExpression( new BinaryExpression( ParameterExpression(“value”) ConstantExpression(2) ) ConstantExpression(10) Runtime time generation f = e.Compile(); Runtime time generation by JIT machine code (e.g. x86) (code actually executed by real CPU)
12
Expression Trees – Hello world!
Dynamically creating an expression tree for () => Console.WriteLine(“Hello world!”) lambda expression: delegate void VoidDelegate(); class Program { static void Main(string[] args) { MethodInfo mi = typeof(Console).GetMethod( "WriteLine", BindingFlags.Public | BindingFlags.Static, null, new Type[] { typeof(string) }, null ); Expression<VoidDelegate> expr = Expression.Lambda<VoidDelegate>( Expression.Call(mi, Expression.Constant("Hello world!") ) VoidDelegate d = expr.Compile(); d(); }
13
Expression Trees – Another Example
delegate void Void1Delegate(int value); Console.Write("Enter a number: "); int number = int.Parse(Console.ReadLine()); MethodInfo mi = typeof(Console).GetMethod( "WriteLine", BindingFlags.Public | BindingFlags.Static, null, new Type[] { typeof(string), typeof(object) }, null ); ParameterExpression param = Expression.Parameter(typeof(int), "valueToAdd"); Expression<Void1Delegate> expr = Expression.Lambda<Void1Delegate>( Expression.Call( mi, Expression.Constant("Hello world! Value is {0}"), Expression.Convert( Expression.Add( param, Expression.Constant(number, typeof(int)) ), typeof(object) ) param Void1Delegate d = expr.Compile(); d(10); d(20);
14
Implementing Generic Complex, etc.
struct IntWrapper { public int v; public IntWrapper(int value) { v = value; } public static IntWrapper operator +(IntWrapper a, IntWrapper b) { return new IntWrapper(a.v + b.v);
15
Implementing Generic Complex, etc. (a Problem)
struct IntWrapper { public int v; public IntWrapper(int value) { v = value; } public static IntWrapper operator +(IntWrapper a, IntWrapper b) { return new IntWrapper(a.v + b.v); Cannot be rewritten to: struct Wrapper<T> { public T v; public Wrapper(T value) { public static Wrapper<T> operator +(Wrapper<T> a, Wrapper<T> b) { return new Wrapper<T>(a.v + b.v);
16
Implementing Generic Complex, etc. (using ExprTree)
using System.Linq.Expressions; struct ValueWrapper<T> { public T v; private static Func<T, T, T> addProxy; static ValueWrapper() { // Creates (a, b) => a + b lambda expression at runtime ParameterExpression paramA = Expression.Parameter(typeof(T), "a"); ParameterExpression paramB = Expression.Parameter(typeof(T), "b"); BinaryExpression addExpr = Expression.Add(paramA, paramB); addProxy = Expression.Lambda<Func<T, T, T>>(addExpr, paramA, paramB).Compile(); } public ValueWrapper(T value) { v = value; public static ValueWrapper<T> operator +(ValueWrapper<T> a, ValueWrapper<T> b) { return new ValueWrapper<T>(addProxy(a.v, b.v));
17
Implementing Generic Complex, etc. (using ExprTree)
using System.Linq.Expressions; struct ValueWrapper<T> { public T v; private static Func<T, T, T> addProxy; static ValueWrapper() { // Creates (a, b) => a + b lambda expression at runtime ParameterExpression paramA = Expression.Parameter(typeof(T), "a"); ParameterExpression paramB = Expression.Parameter(typeof(T), "b"); BinaryExpression addExpr = Expression.Add(paramA, paramB); addProxy = Expression.Lambda<Func<T, T, T>>(addExpr, paramA, paramB).Compile(); } public ValueWrapper(T value) { v = value; public static ValueWrapper<T> operator +(ValueWrapper<T> a, ValueWrapper<T> b) { return new ValueWrapper<T>(addProxy(a.v, b.v));
18
Serialization
19
System.Runtime.Serialization Serialization and Formatters
namespace System.Runtime.Serialization.Formatters.Binary BinaryFormatter namespace System.Runtime.Serialization.Formatters.Soap assembly System.Runtime.Serialization.Formatters.Soap SoapFormatter Serializable objects: Must have SerializableAttribute defined All public and private member fields are serialized – this implies that all of them must be serializable, i.e. have SerializableAttribute defined Fields with NonSerializedAttribute are excluded from default serialization Can implement ISerializable interface to provide their custom serialization public interface IFormatter { void Serialize(Stream serializationStream, object graph); object Deserialize(Stream serializationStream); … }
20
Example: Serialization
[Serializable] public class TestSimpleObject { int member1; string member2; string member3; double member4; [NonSerialized] string member5; public TestSimpleObject() member1 = 11; member2 = "hello"; member3 = "hello"; member4 = ; member5 = "hello world!"; } [OnDeserializing] public void SetDefaults(StreamingContext ctx) { member5 = "DefaultValue"; public void Print() Console.WriteLine("member1 = '{0}'", member1); Console.WriteLine("member2 = '{0}'", member2); Console.WriteLine("member3 = '{0}'", member3); Console.WriteLine("member4 = '{0}'", member4); Console.WriteLine("member5 = '{0}'", member5);
21
Example: Serialization, cont.
using System; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Soap; public class Test { public static void Main() TestSimpleObject obj = new TestSimpleObject(); obj.Print(); Stream stream = File.Open("data.xml", FileMode.Create); SoapFormatter formatter = new SoapFormatter(); formatter.Serialize(stream, obj); stream.Close(); obj = null; // stream = File.Open("data.xml", FileMode.Open); obj = (TestSimpleObject) formatter.Deserialize(stream); }
22
Example: Serialization, cont.
Output of SoapFormatter: <SOAP-ENV:Envelope …> <SOAP-ENV:Body> <a1:TestSimpleObject id="ref-1" xmlns:a1=" <member1>11</member1> <member2 id="ref-3">hello</member2> <member3 href="#ref-3"/> <member4> </member4> </a1:TestSimpleObject> </SOAP-ENV:Body> </SOAP-ENV:Envelope> Output of BinaryFormatter:
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.