C#3.0 – CollectionInitializers Before… List<Employee> lst = new List<Employee>(); Employee john = new Employee(); john.Name = "john"; john.Age = 58; Employee michael = new Employee(); michael.Name = "taro"; michael.Age = 62; lst.Add( john ); lst.Add( michael );
7.
C#3.0 – CollectionInitializers After ! var + オブジェクト初期化子 + コレクション初期化子 var lst = new List<Employee>() { new Employee { Name = "john", Age = 22 }, new Employee { Name = "taro", Age = 24 }, };
2 . 拡張メソッドを使った場合 拡張メソッドの使い方 静的クラス、静的メソッド 第一引数の this キーワード public static class SampleExtensions { public static int Add( this int a, int b ) { return a + b; } } ~ int a = 60; int result = a.Add( 40 ); // 100
15.
2 . 拡張メソッドを使った場合 public class Foo<T> { } public static class FooExtensions { public static void Method( this Foo< string > f, int x ) { Console.WriteLine( x + " かもしれない " ); } public static void Method( this Foo< int > f, int x ) { Console.WriteLine( x + " じゃないと思う " ); } public static void Method<T>( this Foo<T> f, int x ) { Console.WriteLine( x ); } } つづく
16.
2 . 拡張メソッドを使った場合 public void Test() { new Foo< string >().Method( 10 ); new Foo< int >().Method( 100 ); new Foo<Foo< string >>().Method( 1000 ); } 10 かもしれない 100 だと思う 1000
17.
2 . 拡張メソッドを使った場合 好きそうな人向けのおまけ ~ カリー化 拡張メソッドの第一引数部分に f を束縛した状態 本格的なカリー化はクロージャで var f = new Foo< string >(); Action< int > curry = f.Method; curry( 10 ); // 10 かもしれない
実用例~関数の足し算 public Func< string > GetFunc() { string data = "hello"; Func< string > fns = null; fns += (() => data += " world"); fns += (() => data = data.ToUpper()); fns += (() => data = "<b>"+data+"</b>"); return fns; } ~ var f = this .GetFunc(); Console.WriteLine( f() ); // <b>HELLO WORLD</b> “ 責任”を動的に組み替えられる ⇒ ミニマムな Decorator パターン
22.
実用例2~ switch の除去public abstract class Food { } public class ちくわ : Food { } public class ネオちくわ : ちくわ { } public class いも : Food { } public class じゃがいも : いも { } public class みそしる : Food { } ~ public Food Create( string name ) { switch ( name ) { case "taro": return new ネオちくわ (); case "hanako": return new いも (); case "mae": return new みそしる (); default : throw new ArgumentException(); } } Before…
23.
実用例2~ switch の除去private Dictionary< string , Func< Food >> table = new Dictionary< string , Func< Food >>() { { "taro", () => new ネオちくわ () }, { "hanako", () => new いも () }, { "mae", () => new みそしる () } }; public Food Create( string name ) { if ( this .table.ContainsKey( name ) ) return this .table[ name ](); throw new ArgumentException(); } After !