C#のデリゲートとは何ですか?
C#のデリゲートは、メソッドへの参照です。デリゲートは、メソッドへの参照を保持する参照型変数です。参照は実行時に変更できます。
デリゲートは、イベントとコールバックメソッドを実装するために特に使用されます。すべてのデリゲートは、System.Delegateクラスから暗黙的に派生します。
C#でデリゲートを宣言する方法を見てみましょう。
delegate <return type> <delegate-name> <parameter list>
C#でデリゲートを操作する方法を学ぶための例を見てみましょう。
例
using System;
using System.IO;
namespace DelegateAppl {
class PrintString {
static FileStream fs;
static StreamWriter sw;
// delegate declaration
public delegate void printString(string s);
// this method prints to the console
public static void WriteToScreen(string str) {
Console.WriteLine("The String is: {0}", str);
}
//this method prints to a file
public static void WriteToFile(string s) {
fs = new FileStream("c:\\message.txt",
FileMode.Append, FileAccess.Write);
sw = new StreamWriter(fs);
sw.WriteLine(s);
sw.Flush();
sw.Close();
fs.Close();
}
// this method takes the delegate as a parameter and uses it to
// call the methods as required
public static void sendString(printString ps) {
ps("Hello World");
}
static void Main(string[] args) {
printString ps1 = new printString(WriteToScreen);
printString ps2 = new printString(WriteToFile);
sendString(ps1);
sendString(ps2);
Console.ReadKey();
}
}
} 出力
The String is: Hello World
-
C#の名前空間とは何ですか?
名前空間は、ある名前のセットを別の名前のセットから分離する方法を提供するためのものです。名前空間の定義は、次のように、キーワードnamespaceで始まり、その後に名前空間名が続きます- namespace namespace_name { // code declarations } 名前空間を定義する- namespace namespace_name { // code declarations } 以下は、C#で名前空間を使用する方法を示す例です- 例 using System; namespace first_space {
-
C#のデリゲートとは何ですか?
C#のデリゲートは、メソッドへの参照です。デリゲートは、メソッドへの参照を保持する参照型変数です。参照は実行時に変更できます。 デリゲートは、イベントとコールバックメソッドを実装するために特に使用されます。すべてのデリゲートは、System.Delegateクラスから暗黙的に派生します。 C#でデリゲートを宣言する方法を見てみましょう。 delegate <return type> <delegate-name> <parameter list> C#でデリゲートを操作する方法を学ぶための例を見てみましょう。 例 using System; using