ตัวระบุการเข้าถึงสาธารณะ
ตัวระบุการเข้าถึงแบบสาธารณะอนุญาตให้คลาสเปิดเผยตัวแปรสมาชิกและฟังก์ชันของสมาชิกไปยังฟังก์ชันและอ็อบเจ็กต์อื่นๆ สมาชิกสาธารณะทุกคนสามารถเข้าถึงได้จากนอกชั้นเรียน
ตัวอย่าง
using System;
namespace Demo {
class Rectangle {
public double length;
public double width;
public double GetArea() {
return length * width;
}
public void Display() {
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
} //end class Rectangle
class ExecuteRectangle {
static void Main(string[] args) {
Rectangle r = new Rectangle();
r.length = 7;
r.width = 10;
r.Display();
Console.ReadLine();
}
}
} ผลลัพธ์
Length: 7 Width: 10 Area: 70
ตัวระบุการเข้าถึงที่มีการป้องกัน
ตัวระบุการเข้าถึงที่มีการป้องกันช่วยให้คลาสย่อยเข้าถึงตัวแปรสมาชิกและฟังก์ชันสมาชิกของคลาสพื้นฐานได้
ให้เราดูตัวอย่างของตัวแก้ไขการเข้าถึงที่ได้รับการป้องกัน การเข้าถึงสมาชิกที่ได้รับการคุ้มครอง
ตัวอย่าง
using System;
namespace MySpecifiers {
class Demo {
protected string name = "Website";
protected void Display(string str) {
Console.WriteLine("Tabs: " + str);
}
}
class Test : Demo {
static void Main(string[] args) {
Test t = new Test();
Console.WriteLine("Details: " + t.name);
t.Display("Product");
t.Display("Services");
t.Display("Tools");
t.Display("Plugins");
}
}
} ผลลัพธ์
Details: Website Tabs: Product Tabs: Services Tabs: Tools Tabs: Plugins
ตัวระบุการเข้าถึงแบบส่วนตัว
ตัวระบุการเข้าถึงแบบส่วนตัวอนุญาตให้คลาสซ่อนตัวแปรสมาชิกและฟังก์ชันสมาชิกจากฟังก์ชันและอ็อบเจ็กต์อื่นๆ เฉพาะฟังก์ชันของคลาสเดียวกันเท่านั้นที่สามารถเข้าถึงสมาชิกส่วนตัวได้ แม้แต่อินสแตนซ์ของชั้นเรียนก็ไม่สามารถเข้าถึงสมาชิกส่วนตัวได้
ตัวอย่าง
using System;
namespace Demo {
class Rectangle {
//member variables
private double length;
private double width;
public void Acceptdetails() {
length = 10;
width = 15;
}
public double GetArea() {
return length * width;
}
public void Display() {
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}//end class Rectangle
class ExecuteRectangle {
static void Main(string[] args) {
Rectangle r = new Rectangle();
r.Acceptdetails();
r.Display();
Console.ReadLine();
}
}
} ผลลัพธ์
Length: 10 Width: 15 Area: 150