C 索引器與屬性的區別,以及索引器使用方法

2021-07-16 04:37:28 字數 1562 閱讀 6973

索引器允許類或者結構的例項按照與陣列相同的方式進行索引取值,索引器與屬性類似,不同的是索引器的訪問是帶參的。

索引器和陣列比較:

(1)索引器的索引值(index)型別不受限制

(2)索引器允許過載

(3)索引器不是乙個變數

索引器和屬性的不同點

(1)屬性以名稱來標識,索引器以函式形式標識

(2)索引器可以被過載,屬性不可以

(3)索引器不能宣告為static,屬性可以

using system;

using system.collections;

public

class indexerclass

return

null;

}//實現索引器的set方法

set }}

}public

class test

}

字串為下標,對索引器進行操作:
public

class indexerclass

}}public

class test

}

索引器的過載
public

class indexerclass

set

}//2:通過values訪問key

public

intthis[string aname]

}return -1;

}set

}}public

class test

}

多參所引器
using system;

using system.collections;

//入職資訊類

public

class entrantinfo

public

entrantinfo(string name, int num, string department)

public

string name

set

}public

int num

set

}public

string department

set

}}//宣告乙個類entrantinfo的索引器

public

class indexerforentrantinfo

//宣告乙個索引器:以名字和編號查詢訪問部門資訊

public

string

this[string name, int num]

}return

null;

}set

}//宣告乙個索引器:以編號查詢名字和部門

public arraylist this[int num]

}return temp;}}

//還可以宣告多個版本的索引器...

}public

class test

}}

C 索引器與屬性

索引器允許類或結構的例項按照與陣列相同的方式進行索引。索引器類似於屬性,不同之處在於它們的訪問器採用引數。屬性 class sampleclass set 索引器 索引器使得物件可按照與陣列相似的方法進行索引。get 訪問器返回值。set 訪問器分配值。this 關鍵字用於定義索引器。value 關...

索引器與迭代器,屬性的區別

索引器允許類或結構的例項按照與陣列相同的方式進行索引 迭代器主要是為foreach關鍵字服務的 打個比方吧 可能不恰當 加入在桌面上擺上十張紙牌並按照一定的順序編上1 10的號碼,對應的為 0 1 2 3 4 5 6 7 8 9 a b c d e f g h i j 如果是索引我索引第二張返回的就...

索引器與迭代器,屬性的區別

索引器允許類或結構的例項按照與陣列相同的方式進行索引 迭代器主要是為foreach關鍵字服務的 打個比方吧 可能不恰當 加入在桌面上擺上十張紙牌並按照一定的順序編上1 10的號碼,對應的為 0 1 2 3 4 5 6 7 8 9 a b c d e f g h i j 如果是索引我索引第二張返回的就...