類成員可以包括:常數、字段、方法、屬性、事件、索引器、運算符、實例構造函數、析構函數、靜態構造函數和嵌套類型聲明。每個成員都有關聯的可訪問性,它控制能夠訪問該成員的程序文本區域。有五種可能的可訪問性形式。下表概述了這些形式。
形式 直觀含義
public
不限制訪問。
protected
訪問限于該成員所屬的類或從該類派生來的類型。
internal
訪問限于此程序。
protected internal
訪問限于此程序或從該成員所屬的類派生的類型。
private
訪問限于該成員所屬的類型。
示例
using system;
class myclass
{
public myclass() {
console.writeline("instance constructor");
}
public myclass(int value) {
myfield = value;
console.writeline("instance constructor");
}
~myclass() {
console.writeline("destructor");
}
public const int myconst = 12;
public int myfield = 34;
public void mymethod(){
console.writeline("myclass.mymethod");
}
public int myproperty {
get {
return myfield;
}
set {
myfield = value;
}
}
public int this[int index] {
get {
return 0;
}
set {
console.writeline("this[{0}] = {1}", index, value);
}
}
public event eventhandler myevent;
public static myclass operator+(myclass a, myclass b) {
return new myclass(a.myfield + b.myfield);
}
internal class mynestedclass
{}
}
顯示了一個類,它包含了具有各種可訪問性的成員。示例
class test
{
static void main() {
// instance constructor usage
myclass a = new myclass();
myclass b = new myclass(123);
// constant usage
console.writeline("myconst = {0}", myclass.myconst);
// field usage
a.myfield++;
console.writeline("a.myfield = {0}", a.myfield);
// method usage
a.mymethod();
// property usage
a.myproperty++;
console.writeline("a.myproperty = {0}", a.myproperty);
// indexer usage
a[3] = a[1] = a[2];
console.writeline("a[3] = {0}", a[3]);
// event usage
a.myevent += new eventhandler(myhandler);
// overloaded operator usage
myclass c = a + b;
}
static void myhandler(object sender, eventargs e) {
console.writeline("test.myhandler");
}
internal class mynestedclass
{}
}
顯示了這些成員的用法。
新聞熱點
疑難解答