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); } } }
この記事は
現在のアクセス:5059