SlideShare une entreprise Scribd logo
1  sur  41
Expressions и все-все-все
http://sane.habrahabr.ru
http://der-waldgeist.blogspot.com
http://twitter.com/AlexSane
http://www.google.com/profiles/shurickFomin




                                    http://crew.taucraft.com/
Expression
…остальные              trees
 плюшки



             Expression
               Visitor
2+3*4

2+(3*4)
private static void Main()
{
  Func<int, int, int> f = (x, y) => x + y;
  Console.WriteLine(f);
}
System.Func`3[System.Int32,System.Int32,System.Int32]



[CompilerGenerated]
private static int <Main>b__0(int x, int y)
{
    return x+y;
}

private static void Main()
{
    var f = new Func<int, int, int>(Program.<Main>b__0));
    Console.WriteLine(f);
 }
static void Main()
{
    Expression<Func<int, int, int>> f = (x, y) => x + y;
    Console.WriteLine(f);
}

(x, y) => (x + y)



ParameterExpression CS0 = Expression.Parameter(typeof (int), "x");
ParameterExpression CS1 = Expression.Parameter(typeof (int), "y");
Expression<Func<int, int, int>> f =
         Expression.Lambda<Func<int, int, int>>(
                  Expression.Add(CS0, CS1),
                  new ParameterExpression[] {CS0, CS1}
         );
Expression<Func<DateTime, int>> f =
d => (int) Math.Abs((DateTime.Now - d).TotalSeconds);
d => (int) Math.Abs((DateTime.Now - d).TotalSeconds);

ParameterExpression CS0 = Expression.Parameter(typeof (DateTime), "d");
Expression<Func<DateTime, int>> f =
  Expression.Lambda<Func<DateTime, int>>(
    Expression.Convert(
       Expression.Call(
           null,
           (MethodInfo) methodof (Math.Abs),
           new Expression[]
           {
             Expression.Property(
                 Expression.Subtract(
                    Expression.Property(null, (MethodInfo) methodof (DateTime.get_Now)),
                    CS0,
                    (MethodInfo) methodof (DateTime.op_Subtraction)
                 ),
                 (MethodInfo) methodof (TimeSpan.get_TotalSeconds)
             )
           }
       ), typeof (int)
    ), new ParameterExpression[] {CS0} );
Expression
   tree
d => (int) Math.Abs((DateTime.Now - d).TotalSeconds);
.NET 3.0                      .NET 4.0

•   Operators                 •   Blocks
•   Method calls              •   Loops
•   Property getters          •   Try/Catch/Finally
•   Collection initializers   •   Goto/Labels
•   Object initializers       •   Variables
•   Convert/Cast              •   Assignments
•   Constants                 •   If/Then/Else

          (x,y)=>x+y              (x,y) => { return x+y; }*
ExpressionVisitor
protected virtual Expression VisitBinary(BinaryExpression b)
{
   Expression left = this.Visit(b.Left);
   Expression right = this.Visit(b.Right);
   return b;
}
protected virtual Expression VisitBinary(BinaryExpression b)
{
   Expression left = this.Visit(b.Left);
   Expression right = this.Visit(b.Right);
   if (left != b.Left || right != b.Right)
   {
         return Expression.MakeBinary(
                  b.NodeType, left, right, b.Method
         );
   }
    return b;
}
IQueryable<Tree> forest = // ...
var queryable = from tree in forest
                where tree.HasHollow
                select tree.ColectSomeHoney();

var queryable = forest.Where(tree => tree.HasHollow)
                .Select(tree => tree.ColectSomeHoney());

var queryable = Queryable.Select(
  Queryable.Where(forest, tree => tree.HasHollow),
     tree => tree.ColectSomeHoney() );

var queryable = Enumerable.Select(
  Enumerable.Where(forest.AsEnumerable (), tree => tree.HasHollow),
     tree => tree.ColectSomeHoney() );
internal override Expression VisitMethodCall(MethodCallExpression m)
{
    Expression instance = base.VisitMethodCall(m);
    if (m.Method.DeclaringType == typeof(Queryable))
    {
          MethodInfo info = FindEnumerableMethod(m.Method);
          return Expression.Call(instance, info, source);
    }
    return m;
}
internal override Expression VisitMethodCall(MethodCallExpression m)
{
    Expression instance = base.VisitMethodCall(m);

    if (m.Method.DeclaringType == typeof(Queryable))
    {
          MethodInfo info = FindEnumerableMethod(m.Method);
          return Expression.Call(instance, info, source);
    }
    return m;
}
Compiled expressions
string PasswordPhrase(bool isBear)
{
   return string.Format("{0} очень любит {1}",
      isBear ? "Мишка" : "Ослик",
      isBear ? "мёд" : "йод");
}
ILGenerator generator = //...
var label1 = generator.DefineLabel();
var label2 = generator.DefineLabel();
var label3 = generator.DefineLabel();
var label4 = generator.DefineLabel();
generator.Emit(OpCodes.Ldstr, "{0} очень любит {1}");
generator.Emit(OpCodes.Ldarg_1);
generator.Emit(OpCodes.Brtrue_S, label1);
generator.Emit(OpCodes.Ldstr, "Мишка");
generator.Emit(OpCodes.Br_S, label2);
generator.MarkLabel(label1);
generator.Emit(OpCodes.Ldstr, ”Ослик");
generator.MarkLabel(label2);
generator.Emit(OpCodes.Ldarg_1);
generator.Emit(OpCodes.Brtrue_S, label3);
generator.MarkLabel(label3);
generator.Emit(OpCodes.Ldstr, ”мёд");
generator.Emit(OpCodes.Br_S, label4);
generator.Emit(OpCodes.Ldstr, "йод");
generator.MarkLabel(label4);
generator.EmitCall(OpCodes.Call, typeof(String).GetMethod("Format"), new[] { typeof(string), typeof(ob
     ject), typeof(object) });
generator.Emit(OpCodes.Ret);
Func<bool, string> Emit()
{
  var isBear = Expression.Parameter(typeof (bool), "isBear");
  var lambda = Expression.Lambda<Func<bool, string>>(
   Expression.Call(
     Method(() => string.Format("", null, null)),
       Expression.Constant("{0} очень любит {1}"),
       Expression.Condition(isBear, Expression.Constant("Мишка"),
                              Expression.Constant("Ослик")),
         Expression.Condition(isBear, Expression.Constant("мёд"), Expression.C
onstant("йод") )
      )
   );
  Func<bool, string> func = lambda.Compile();
  return func;
}
Reflection in compile time
public class Tree
{
    public Honey ColectSomeHoney()
    {
           //...
           return new Honey();
    }
}
private static void Main()
{
    MethodInfo method =
      typeof(Tree).GetMethod( "ColectSomeHoney",
         BindingFlags.Public | BindingFlags.Instance
      );
}
Reflection in compile time
public class Tree
{
   public Honey CollectSomeHoney()
   {
         //...
         return new Honey();
   }
}
private static void Main()
{
    MethodInfo method =
     typeof(Tree).GetMethod( "ColectSomeHoney",
        BindingFlags.Public | BindingFlags.Instance
     );
}
Reflection in compile time
public class Tree
{
    public Honey CollectSomeHoney()
    {
          //...
          return new Honey();
    }
}
private static void Main()
{
    MethodInfo method =
     typeof(Tree).GetMethod( "ColectSomeHoney",
        BindingFlags.Public | BindingFlags.Instance
     );
}
Reflection in compile time
private static void Main()
{
  var method = GetMethod<Tree>(x => x.ColectSomeHoney());
}
public static MethodInfo GetMethod<T>(Expression<Action<T>> e)
{
  return ((MethodCallExpression) e.Body)
     .Method;
}
Reflection in compile time
private static void Main()
{
  var method = GetMethod<Tree>(x => x.CollectSomeHoney());
}
public static MethodInfo GetMethod<T>(Expression<Action<T>> e)
{
  return ((MethodCallExpression) e.Body)
     .Method;
}
IQueryable
interface IQueryable<T> : IEnumerable<T> , IQueryable
{
    Type ElementType { get; }
    Expression Expression { get; }
    IQueryProvider Provider { get; }
}

interface IQueryProvider
{
    IQueryable CreateQuery(Expression e) ;
    IQueryable<T> CreateQuery<T> (Expression e);
    object Execute (Expression expression);
    object Execute (Expression expression);
}
IQueryable
Expressions в C# — impress yourself!




                      http://habrahabr.ru/blogs/net/83169/
LINQ: Building an IQueryable provider
                series




        http://blogs.msdn.com/b/mattwar/archive/2008/11/18/linq-links.aspx
Винни-Пух и Все-Все-все




                  ISBN: 978-5-17-064151-2
Expressions и все-все-все in C

Contenu connexe

Tendances

TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDBTDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDBtdc-globalcode
 
Closure, Higher-order function in Swift
Closure, Higher-order function in SwiftClosure, Higher-order function in Swift
Closure, Higher-order function in SwiftSeongGyu Jo
 
Collection v3
Collection v3Collection v3
Collection v3Sunil OS
 
Patterns for slick database applications
Patterns for slick database applicationsPatterns for slick database applications
Patterns for slick database applicationsSkills Matter
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기진성 오
 
Collections Framework
Collections FrameworkCollections Framework
Collections FrameworkSunil OS
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to PythonUC San Diego
 
Implementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with SlickImplementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with SlickHermann Hueck
 
Using Scala Slick at FortyTwo
Using Scala Slick at FortyTwoUsing Scala Slick at FortyTwo
Using Scala Slick at FortyTwoEishay Smith
 
Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7Paulo Morgado
 
Beginners python cheat sheet - Basic knowledge
Beginners python cheat sheet - Basic knowledge Beginners python cheat sheet - Basic knowledge
Beginners python cheat sheet - Basic knowledge O T
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Datagreenwop
 
From java to kotlin beyond alt+shift+cmd+k - Droidcon italy
From java to kotlin beyond alt+shift+cmd+k - Droidcon italyFrom java to kotlin beyond alt+shift+cmd+k - Droidcon italy
From java to kotlin beyond alt+shift+cmd+k - Droidcon italyFabio Collini
 
Python3 cheatsheet
Python3 cheatsheetPython3 cheatsheet
Python3 cheatsheetGil Cohen
 
Python 2.5 reference card (2009)
Python 2.5 reference card (2009)Python 2.5 reference card (2009)
Python 2.5 reference card (2009)gekiaruj
 
Groovy grails types, operators, objects
Groovy grails types, operators, objectsGroovy grails types, operators, objects
Groovy grails types, operators, objectsHusain Dalal
 

Tendances (20)

TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDBTDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
 
Closure, Higher-order function in Swift
Closure, Higher-order function in SwiftClosure, Higher-order function in Swift
Closure, Higher-order function in Swift
 
Collection v3
Collection v3Collection v3
Collection v3
 
Patterns for slick database applications
Patterns for slick database applicationsPatterns for slick database applications
Patterns for slick database applications
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기
 
PDBC
PDBCPDBC
PDBC
 
Collections Framework
Collections FrameworkCollections Framework
Collections Framework
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
Implementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with SlickImplementing a many-to-many Relationship with Slick
Implementing a many-to-many Relationship with Slick
 
Using Scala Slick at FortyTwo
Using Scala Slick at FortyTwoUsing Scala Slick at FortyTwo
Using Scala Slick at FortyTwo
 
Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7
 
What's New In C# 7
What's New In C# 7What's New In C# 7
What's New In C# 7
 
Beginners python cheat sheet - Basic knowledge
Beginners python cheat sheet - Basic knowledge Beginners python cheat sheet - Basic knowledge
Beginners python cheat sheet - Basic knowledge
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Data
 
From java to kotlin beyond alt+shift+cmd+k - Droidcon italy
From java to kotlin beyond alt+shift+cmd+k - Droidcon italyFrom java to kotlin beyond alt+shift+cmd+k - Droidcon italy
From java to kotlin beyond alt+shift+cmd+k - Droidcon italy
 
Python3 cheatsheet
Python3 cheatsheetPython3 cheatsheet
Python3 cheatsheet
 
C# 7
C# 7C# 7
C# 7
 
Python 2.5 reference card (2009)
Python 2.5 reference card (2009)Python 2.5 reference card (2009)
Python 2.5 reference card (2009)
 
Groovy grails types, operators, objects
Groovy grails types, operators, objectsGroovy grails types, operators, objects
Groovy grails types, operators, objects
 
Pooya Khaloo Presentation on IWMC 2015
Pooya Khaloo Presentation on IWMC 2015Pooya Khaloo Presentation on IWMC 2015
Pooya Khaloo Presentation on IWMC 2015
 

Similaire à Expressions и все-все-все in C

HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6Dmitry Soshnikov
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)James Titcumb
 
7 Habits For a More Functional Swift
7 Habits For a More Functional Swift7 Habits For a More Functional Swift
7 Habits For a More Functional SwiftJason Larsen
 
Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...
Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...
Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...James Titcumb
 
Tips and Tricks of Developing .NET Application
Tips and Tricks of Developing .NET ApplicationTips and Tricks of Developing .NET Application
Tips and Tricks of Developing .NET ApplicationJoni
 
Les nouveautés de C# 6
Les nouveautés de C# 6Les nouveautés de C# 6
Les nouveautés de C# 6Microsoft
 
Ast transformations
Ast transformationsAst transformations
Ast transformationsHamletDRC
 
C# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewC# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewPaulo Morgado
 
Pragmatic metaprogramming
Pragmatic metaprogrammingPragmatic metaprogramming
Pragmatic metaprogrammingMårten Rånge
 
関数潮流(Function Tendency)
関数潮流(Function Tendency)関数潮流(Function Tendency)
関数潮流(Function Tendency)riue
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6Dmitry Soshnikov
 
Generics and Inference
Generics and InferenceGenerics and Inference
Generics and InferenceRichard Fox
 
Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."
Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."
Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."sjabs
 

Similaire à Expressions и все-все-все in C (20)

HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
 
7 Habits For a More Functional Swift
7 Habits For a More Functional Swift7 Habits For a More Functional Swift
7 Habits For a More Functional Swift
 
Elm: give it a try
Elm: give it a tryElm: give it a try
Elm: give it a try
 
Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...
Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...
Mirror, mirror on the wall - Building a new PHP reflection library (Nomad PHP...
 
Tips and Tricks of Developing .NET Application
Tips and Tricks of Developing .NET ApplicationTips and Tricks of Developing .NET Application
Tips and Tricks of Developing .NET Application
 
Les nouveautés de C# 6
Les nouveautés de C# 6Les nouveautés de C# 6
Les nouveautés de C# 6
 
Ast transformations
Ast transformationsAst transformations
Ast transformations
 
C# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewC# 6.0 - April 2014 preview
C# 6.0 - April 2014 preview
 
Java VS Python
Java VS PythonJava VS Python
Java VS Python
 
Functional programming with php7
Functional programming with php7Functional programming with php7
Functional programming with php7
 
Pragmatic metaprogramming
Pragmatic metaprogrammingPragmatic metaprogramming
Pragmatic metaprogramming
 
関数潮流(Function Tendency)
関数潮流(Function Tendency)関数潮流(Function Tendency)
関数潮流(Function Tendency)
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6
 
Generics and Inference
Generics and InferenceGenerics and Inference
Generics and Inference
 
New C# features
New C# featuresNew C# features
New C# features
 
Using the Windows 8 Runtime from C++
Using the Windows 8 Runtime from C++Using the Windows 8 Runtime from C++
Using the Windows 8 Runtime from C++
 
How te bring common UI patterns to ADF
How te bring common UI patterns to ADFHow te bring common UI patterns to ADF
How te bring common UI patterns to ADF
 
Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."
Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."
Kamil Chmielewski, Jacek Juraszek - "Hadoop. W poszukiwaniu złotego młotka."
 

Plus de Ciklum Ukraine

"How keep normal blood pressure using TDD" By Roman Loparev
"How keep normal blood pressure using TDD" By Roman Loparev"How keep normal blood pressure using TDD" By Roman Loparev
"How keep normal blood pressure using TDD" By Roman LoparevCiklum Ukraine
 
"Through the three circles of the it hell" by Roman Liashenko
"Through the three circles of the it hell" by Roman Liashenko"Through the three circles of the it hell" by Roman Liashenko
"Through the three circles of the it hell" by Roman LiashenkoCiklum Ukraine
 
Alex Pazhyn: Google_Material_Design
Alex Pazhyn: Google_Material_DesignAlex Pazhyn: Google_Material_Design
Alex Pazhyn: Google_Material_DesignCiklum Ukraine
 
Introduction to amazon web services for developers
Introduction to amazon web services for developersIntroduction to amazon web services for developers
Introduction to amazon web services for developersCiklum Ukraine
 
Your 1st Apple watch Application
Your 1st Apple watch ApplicationYour 1st Apple watch Application
Your 1st Apple watch ApplicationCiklum Ukraine
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven DevelopmentCiklum Ukraine
 
Back to the future: ux trends 2015
Back to the future: ux trends 2015Back to the future: ux trends 2015
Back to the future: ux trends 2015Ciklum Ukraine
 
Developing high load systems using C++
Developing high load systems using C++Developing high load systems using C++
Developing high load systems using C++Ciklum Ukraine
 
Collection view layout
Collection view layoutCollection view layout
Collection view layoutCiklum Ukraine
 
Introduction to auto layout
Introduction to auto layoutIntroduction to auto layout
Introduction to auto layoutCiklum Ukraine
 
Unit Testing: Special Cases
Unit Testing: Special CasesUnit Testing: Special Cases
Unit Testing: Special CasesCiklum Ukraine
 
Model-View-Controller: Tips&Tricks
Model-View-Controller: Tips&TricksModel-View-Controller: Tips&Tricks
Model-View-Controller: Tips&TricksCiklum Ukraine
 
Future of Outsourcing report published in The Times featuring Ciklum's CEO To...
Future of Outsourcing report published in The Times featuring Ciklum's CEO To...Future of Outsourcing report published in The Times featuring Ciklum's CEO To...
Future of Outsourcing report published in The Times featuring Ciklum's CEO To...Ciklum Ukraine
 
Михаил Попчук "Cкрытые резервы команд или 1+1=3"
Михаил Попчук "Cкрытые резервы команд или 1+1=3"Михаил Попчук "Cкрытые резервы команд или 1+1=3"
Михаил Попчук "Cкрытые резервы команд или 1+1=3"Ciklum Ukraine
 

Plus de Ciklum Ukraine (20)

"How keep normal blood pressure using TDD" By Roman Loparev
"How keep normal blood pressure using TDD" By Roman Loparev"How keep normal blood pressure using TDD" By Roman Loparev
"How keep normal blood pressure using TDD" By Roman Loparev
 
"Through the three circles of the it hell" by Roman Liashenko
"Through the three circles of the it hell" by Roman Liashenko"Through the three circles of the it hell" by Roman Liashenko
"Through the three circles of the it hell" by Roman Liashenko
 
Alex Pazhyn: Google_Material_Design
Alex Pazhyn: Google_Material_DesignAlex Pazhyn: Google_Material_Design
Alex Pazhyn: Google_Material_Design
 
Introduction to amazon web services for developers
Introduction to amazon web services for developersIntroduction to amazon web services for developers
Introduction to amazon web services for developers
 
Your 1st Apple watch Application
Your 1st Apple watch ApplicationYour 1st Apple watch Application
Your 1st Apple watch Application
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Back to the future: ux trends 2015
Back to the future: ux trends 2015Back to the future: ux trends 2015
Back to the future: ux trends 2015
 
Developing high load systems using C++
Developing high load systems using C++Developing high load systems using C++
Developing high load systems using C++
 
Collection view layout
Collection view layoutCollection view layout
Collection view layout
 
Introduction to auto layout
Introduction to auto layoutIntroduction to auto layout
Introduction to auto layout
 
Groovy on Android
Groovy on AndroidGroovy on Android
Groovy on Android
 
Unit Testing: Special Cases
Unit Testing: Special CasesUnit Testing: Special Cases
Unit Testing: Special Cases
 
Material design
Material designMaterial design
Material design
 
Kanban development
Kanban developmentKanban development
Kanban development
 
Mobile sketching
Mobile sketching Mobile sketching
Mobile sketching
 
More UX in our life
More UX in our lifeMore UX in our life
More UX in our life
 
Model-View-Controller: Tips&Tricks
Model-View-Controller: Tips&TricksModel-View-Controller: Tips&Tricks
Model-View-Controller: Tips&Tricks
 
Unit Tesing in iOS
Unit Tesing in iOSUnit Tesing in iOS
Unit Tesing in iOS
 
Future of Outsourcing report published in The Times featuring Ciklum's CEO To...
Future of Outsourcing report published in The Times featuring Ciklum's CEO To...Future of Outsourcing report published in The Times featuring Ciklum's CEO To...
Future of Outsourcing report published in The Times featuring Ciklum's CEO To...
 
Михаил Попчук "Cкрытые резервы команд или 1+1=3"
Михаил Попчук "Cкрытые резервы команд или 1+1=3"Михаил Попчук "Cкрытые резервы команд или 1+1=3"
Михаил Попчук "Cкрытые резервы команд или 1+1=3"
 

Dernier

The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 

Dernier (20)

The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 

Expressions и все-все-все in C

  • 3. Expression …остальные trees плюшки Expression Visitor
  • 4.
  • 6. private static void Main() { Func<int, int, int> f = (x, y) => x + y; Console.WriteLine(f); } System.Func`3[System.Int32,System.Int32,System.Int32] [CompilerGenerated] private static int <Main>b__0(int x, int y) { return x+y; } private static void Main() { var f = new Func<int, int, int>(Program.<Main>b__0)); Console.WriteLine(f); }
  • 7. static void Main() { Expression<Func<int, int, int>> f = (x, y) => x + y; Console.WriteLine(f); } (x, y) => (x + y) ParameterExpression CS0 = Expression.Parameter(typeof (int), "x"); ParameterExpression CS1 = Expression.Parameter(typeof (int), "y"); Expression<Func<int, int, int>> f = Expression.Lambda<Func<int, int, int>>( Expression.Add(CS0, CS1), new ParameterExpression[] {CS0, CS1} );
  • 8. Expression<Func<DateTime, int>> f = d => (int) Math.Abs((DateTime.Now - d).TotalSeconds);
  • 9. d => (int) Math.Abs((DateTime.Now - d).TotalSeconds); ParameterExpression CS0 = Expression.Parameter(typeof (DateTime), "d"); Expression<Func<DateTime, int>> f = Expression.Lambda<Func<DateTime, int>>( Expression.Convert( Expression.Call( null, (MethodInfo) methodof (Math.Abs), new Expression[] { Expression.Property( Expression.Subtract( Expression.Property(null, (MethodInfo) methodof (DateTime.get_Now)), CS0, (MethodInfo) methodof (DateTime.op_Subtraction) ), (MethodInfo) methodof (TimeSpan.get_TotalSeconds) ) } ), typeof (int) ), new ParameterExpression[] {CS0} );
  • 10. Expression tree
  • 11. d => (int) Math.Abs((DateTime.Now - d).TotalSeconds);
  • 12. .NET 3.0 .NET 4.0 • Operators • Blocks • Method calls • Loops • Property getters • Try/Catch/Finally • Collection initializers • Goto/Labels • Object initializers • Variables • Convert/Cast • Assignments • Constants • If/Then/Else (x,y)=>x+y (x,y) => { return x+y; }*
  • 13.
  • 15. protected virtual Expression VisitBinary(BinaryExpression b) { Expression left = this.Visit(b.Left); Expression right = this.Visit(b.Right); return b; }
  • 16. protected virtual Expression VisitBinary(BinaryExpression b) { Expression left = this.Visit(b.Left); Expression right = this.Visit(b.Right); if (left != b.Left || right != b.Right) { return Expression.MakeBinary( b.NodeType, left, right, b.Method ); } return b; }
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22. IQueryable<Tree> forest = // ... var queryable = from tree in forest where tree.HasHollow select tree.ColectSomeHoney(); var queryable = forest.Where(tree => tree.HasHollow) .Select(tree => tree.ColectSomeHoney()); var queryable = Queryable.Select( Queryable.Where(forest, tree => tree.HasHollow), tree => tree.ColectSomeHoney() ); var queryable = Enumerable.Select( Enumerable.Where(forest.AsEnumerable (), tree => tree.HasHollow), tree => tree.ColectSomeHoney() );
  • 23. internal override Expression VisitMethodCall(MethodCallExpression m) { Expression instance = base.VisitMethodCall(m); if (m.Method.DeclaringType == typeof(Queryable)) { MethodInfo info = FindEnumerableMethod(m.Method); return Expression.Call(instance, info, source); } return m; }
  • 24. internal override Expression VisitMethodCall(MethodCallExpression m) { Expression instance = base.VisitMethodCall(m); if (m.Method.DeclaringType == typeof(Queryable)) { MethodInfo info = FindEnumerableMethod(m.Method); return Expression.Call(instance, info, source); } return m; }
  • 25.
  • 26.
  • 27. Compiled expressions string PasswordPhrase(bool isBear) { return string.Format("{0} очень любит {1}", isBear ? "Мишка" : "Ослик", isBear ? "мёд" : "йод"); }
  • 28. ILGenerator generator = //... var label1 = generator.DefineLabel(); var label2 = generator.DefineLabel(); var label3 = generator.DefineLabel(); var label4 = generator.DefineLabel(); generator.Emit(OpCodes.Ldstr, "{0} очень любит {1}"); generator.Emit(OpCodes.Ldarg_1); generator.Emit(OpCodes.Brtrue_S, label1); generator.Emit(OpCodes.Ldstr, "Мишка"); generator.Emit(OpCodes.Br_S, label2); generator.MarkLabel(label1); generator.Emit(OpCodes.Ldstr, ”Ослик"); generator.MarkLabel(label2); generator.Emit(OpCodes.Ldarg_1); generator.Emit(OpCodes.Brtrue_S, label3); generator.MarkLabel(label3); generator.Emit(OpCodes.Ldstr, ”мёд"); generator.Emit(OpCodes.Br_S, label4); generator.Emit(OpCodes.Ldstr, "йод"); generator.MarkLabel(label4); generator.EmitCall(OpCodes.Call, typeof(String).GetMethod("Format"), new[] { typeof(string), typeof(ob ject), typeof(object) }); generator.Emit(OpCodes.Ret);
  • 29. Func<bool, string> Emit() { var isBear = Expression.Parameter(typeof (bool), "isBear"); var lambda = Expression.Lambda<Func<bool, string>>( Expression.Call( Method(() => string.Format("", null, null)), Expression.Constant("{0} очень любит {1}"), Expression.Condition(isBear, Expression.Constant("Мишка"), Expression.Constant("Ослик")), Expression.Condition(isBear, Expression.Constant("мёд"), Expression.C onstant("йод") ) ) ); Func<bool, string> func = lambda.Compile(); return func; }
  • 30. Reflection in compile time public class Tree { public Honey ColectSomeHoney() { //... return new Honey(); } } private static void Main() { MethodInfo method = typeof(Tree).GetMethod( "ColectSomeHoney", BindingFlags.Public | BindingFlags.Instance ); }
  • 31. Reflection in compile time public class Tree { public Honey CollectSomeHoney() { //... return new Honey(); } } private static void Main() { MethodInfo method = typeof(Tree).GetMethod( "ColectSomeHoney", BindingFlags.Public | BindingFlags.Instance ); }
  • 32. Reflection in compile time public class Tree { public Honey CollectSomeHoney() { //... return new Honey(); } } private static void Main() { MethodInfo method = typeof(Tree).GetMethod( "ColectSomeHoney", BindingFlags.Public | BindingFlags.Instance ); }
  • 33. Reflection in compile time private static void Main() { var method = GetMethod<Tree>(x => x.ColectSomeHoney()); } public static MethodInfo GetMethod<T>(Expression<Action<T>> e) { return ((MethodCallExpression) e.Body) .Method; }
  • 34. Reflection in compile time private static void Main() { var method = GetMethod<Tree>(x => x.CollectSomeHoney()); } public static MethodInfo GetMethod<T>(Expression<Action<T>> e) { return ((MethodCallExpression) e.Body) .Method; }
  • 35. IQueryable interface IQueryable<T> : IEnumerable<T> , IQueryable { Type ElementType { get; } Expression Expression { get; } IQueryProvider Provider { get; } } interface IQueryProvider { IQueryable CreateQuery(Expression e) ; IQueryable<T> CreateQuery<T> (Expression e); object Execute (Expression expression); object Execute (Expression expression); }
  • 37.
  • 38. Expressions в C# — impress yourself! http://habrahabr.ru/blogs/net/83169/
  • 39. LINQ: Building an IQueryable provider series http://blogs.msdn.com/b/mattwar/archive/2008/11/18/linq-links.aspx
  • 40. Винни-Пух и Все-Все-все ISBN: 978-5-17-064151-2