// 下階層用テンプレート #topicpath ---- //ここにコンテンツを記述します。 #contents **C#はDelegateを言語でサポートしてるみたい [#ib7cd4ac] C#では「delegate」という機構で、実装の切替をすることが言語仕様でサポートされてるみたいです。いわゆるオブジェクト指向でいう、実装をインタフェースつかって切り替えるってヤツです。Javaで書くとこんな感じ。 package console_application1; public class Program { public static void main(String[] args) { Base plus = new Plus(); Base mult = new Mult(); calc(2, 3, plus); calc(2, 3, mult); } public static void calc(int x, int y, Base instance) { int result = instance.method(x, y); System.out.println(result); } } interface Base { int method(int x, int y); } class Plus implements Base { public int method(int x, int y) { return x + y; } } class Mult implements Base { public int method(int x, int y) { return x * y; } } もちろんC#でdelegateを使わないで書くこともできます。こんな感じですね。 using System; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Base plus = new Plus(); Base mult = new Mult(); calc(2,3, plus); calc(2,3, mult); } public static void calc(int x, int y, Base instance) { int result=instance.method(x,y); Console.WriteLine(result); } } interface Base { int method(int x, int y); } class Plus : Base { public int method(int x, int y) { return x + y; } } class Mult : Base { public int method(int x, int y) { return x * y; } } } JavaとC#はほとんど書き方が同じでラクチンです さてこれをC#のdelegateでかくとこんな感じみたいです using System; namespace ConsoleApplication1 { delegate int Calculator(int x, int y);//delegateの宣言 class CalculatorBase { public int methodMult(int x, int y) { return x * y; } public int methodPlus(int x, int y) { return x + y; } } class Program { static void Main(string[] args) { CalculatorBase calculator = new CalculatorBase(); calc(2, 3, new Calculator(calculator.methodPlus)); calc(2, 3, new Calculator(calculator.methodMult)); } public static void calc(int x, int y, Calculator instance) { int result=instance(x,y); Console.WriteLine(result); } } } **関連リンク [#oa8b34d8] -[[@IT:連載 改訂版 C#入門 第13章 処理を委譲するデリゲート>http://www.atmarkit.co.jp/fdotnet/csharp_abc2/csabc2_013/cs2_013_03.html]] ---- この記事は #vote(おもしろかった,そうでもない) - C#の中カッコを行変えするのが慣れないなぁ。 -- [[きの]] &new{2010-09-23 (木) 17:14:59}; #comment #topicpath SIZE(10){現在のアクセス:&counter;}