C#のインデクサーとは何ですか?
インデクサーを使用すると、配列などのオブジェクトにインデックスを付けることができます。
構文を見てみましょう-
element-type this[int index] {
// The get accessor.
get {
// return the value specified by index
}
// The set accessor.
set {
// set the value specified by index
}
} 以下は、C#でインデクサーを実装する方法を示す例です-
例
using System;
namespace Demo {
class Program {
private string[] namelist = new string[size];
static public int size = 10;
public Program() {
for (int i = 0; i < size; i++)
namelist[i] = "N. A.";
}
public string this[int index] {
get {
string tmp;
if( index >= 0 && index <= size-1 ) {
tmp = namelist[index];
} else {
tmp = "";
}
return ( tmp );
}
set {
if( index >= 0 && index <= size-1 ) {
namelist[index] = value;
}
}
}
static void Main(string[] args) {
Program names = new Program();
names[0] = "Tom";
names[1] = "Jacob";
names[2] = "Jack";
names[3] = "Amy";
names[4] = "Katy";
names[5] = "Taylor";
names[6] = "Brad";
names[7] = "Scarlett";
names[8] = "James";
for ( int i = 0; i < Program.size; i++ ) {
Console.WriteLine(names[i]);
}
Console.ReadKey();
}
}
} 出力
Tom Jacob Jack Amy Katy Taylor Brad Scarlett James N. A.
-
C#のコンテキストキーワードとは何ですか?
C#では、getやsetなどの一部の識別子は、コードのコンテキストで特別な意味を持ち、コンテキストキーワードと呼ばれます。 以下は、コンテキストキーワードを示す表です- コンテキストキーワード 追加 エイリアス 昇順 降順 動的 から get グローバル グループ に 参加 レット 注文者 部分的(タイプ) partial(method) 削除 選択 設定
-
C#の条件付き属性とは何ですか?
属性は、コンパイラ命令などのメタデータや、コメント、説明、メソッド、クラスなどの他の情報をプログラムに追加するために使用されます。 この事前定義された属性は、実行が指定された前処理識別子に依存する条件付きメソッドをマークします。 DebugやTraceなどの指定された値に応じて、メソッド呼び出しの条件付きコンパイルが発生します。たとえば、コードのデバッグ中に変数の値を表示します。 以下は、条件付き属性の構文です- [Conditional( conditionalSymbol )] 条件付き属性の操作方法を見てみましょう- 例 #define DEBUG us