C#匿名メソッド
匿名メソッドは、コードブロックをデリゲートパラメータとして渡す手法を提供します。匿名メソッドとは、名前のないメソッドであり、本文のみです。
delegate void NumberChanger(int n);
...
NumberChanger nc = delegate(int x) {
Console.WriteLine("Anonymous Method: {0}", x);
}; using System;
delegate void NumberChanger(int n);
namespace DelegateAppl {
class Demo {
static int num = 10;
public static void AddNum(int p) {
num += p;
Console.WriteLine("Named Method: {0}", num);
}
public static void MultNum(int q) {
num *= q;
Console.WriteLine("Named Method: {0}", num);
}
public static int getNum() {
return num;
}
static void Main(string[] args) {
//create delegate instances using anonymous method
NumberChanger nc = delegate(int x) {
Console.WriteLine("Anonymous Method: {0}", x);
};
//calling the delegate using the anonymous method
nc(10);
//instantiating the delegate using the named methods
nc = new NumberChanger(AddNum);
//calling the delegate using the named methods
nc(5);
//instantiating the delegate using another named methods
nc = new NumberChanger(MultNum);
//calling the delegate using the named methods
nc(2);
Console.ReadKey();
}
}
} Anonymous Method: 10 Named Method: 15 Named Method: 30
-
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-