2008年3月17日

[Reading Notes]Reading Notes for [C# 3.0 Packet Reference] - 1

  1. Lamba Expressions
    1. Outer variables(Captured variables)

    2. Lamba Expression can reference local variables and paramaters of the method in which it is defined. In the following example, factor is called outer variable(captured variables).
      void Foo(){
      int factor = 2;
      Func<int, int> multiplier = n => n * factor;
      }
    3. A captured variable is evaluated when the Lamba expression is invoked, not evaluated when it's been captured.
    4. A captured variable's lifetime is extended to that of delegate captrues it.
      FuncFoo(){ int i = 0; return ()=>i++;}
      static void Main(){
      Func foo = Foo();
      Console.WriteLine(foo());//0
      Console.WriteLine(foo());//1
      }
  2. Anonymous Methods
    1. Sample:
      delegate int AnonymousFunc(int i);
      AnonymousFunc = (int x) => {return x*x;};
    2. Anonymous methods captures variables like Lamba Expressions do.
  3. Extension Methods
    1. Extension methods extend existing types with new methods, without altering original type.
    2. Syntax:
      public static class StringExtensions{
      public static bool IsNullOrEmpty(this String s){
      return (s == null s.CompareTo(String.Empty) == 0);
      }...}
    3. A compatible instance method always take precedence over an extended version.
      class Test{
      void Foo(object a){...} //this method always take precedence
      }
      static class Extensions{
      void Foo(this Test t,int x){...}
      }
  4. Anonymous Types
    1. A simple class created on the fly
    2. Syntax:
      var person = new {Name="Michael",Age=32,Class="Programmer"};
      int age = 32;
      var person2 = new {Name="Michael",Age = age; Class="Programmer"};
    3. Anonymous Types are used primarily when writing LINQ

    沒有留言:

    Blog Archive

    About Me