C#の匿名メソッド
C#の匿名メソッドを使用して、C#のデリゲートパラメーターとしてコードブロックを渡します。匿名メソッドとは、名前のないメソッドであり、本文のみです。
delegate void DemoMethod(int n);
...
DemoMethod dm = delegate(int a) {
Console.WriteLine("Our Anonymous Method: {0}", a);
}; 上に示したように、以下は匿名メソッドの本体です-
Console.WriteLine("Our Anonymous Method: {0}", a); 次のコードを実行して、C#で匿名メソッドを実装してみてください-
using System;
delegate void Demo(int n);
namespace MyDelegate {
class TestDelegate {
static int num = 10;
public static void DisplayAdd(int p) {
num += p;
Console.WriteLine("Named Method: {0}", num);
}
public static void DisplayMult(int q) {
num *= q;
Console.WriteLine("Named Method: {0}", num);
}
public static int getNum() {
return num;
}
static void Main(string[] args) {
Demo dm = delegate(int x) {
Console.WriteLine("Anonymous Method: {0}", x);
};
//calling the delegate using the anonymous method
dm(15);
//instantiating the delegate using the named methods
dm = new Demo(DisplayAdd);
//calling the delegate using the named methods
dm(10);
//instantiating the delegate using another named methods
dm = new Demo(DisplayMult);
//calling the delegate using the named methods
dm(4);
Console.ReadKey();
}
}
} Anonymous Method: 15 Named Method: 20 Named Method: 80
-
JavaScriptオブジェクトメソッド
JavaScriptオブジェクトメソッドは、オブジェクトに対して実行できるアクションです。 以下は、JavaScriptのオブジェクトに存在するメソッドを示すコードです- 例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <
-
JavaScriptでメソッドを共有する
メソッドは、オブジェクトのプロトタイププロパティにアタッチすることで共有できます。これらのメソッドは、オブジェクトのすべてのインスタンス間で共有されます。 以下はJavaScriptでメソッドを共有するためのコードです- 例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-