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
21. 実用例~関数の足し算 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 !