Home > C# > โปรแกรม C# Access Modifiers: Protected

โปรแกรม C# Access Modifiers: Protected

February 13, 2011 No Comments

คำว่า protected เป็น ?member access modifier อีกรูปแบบหนึ่ง ซึ่ง protected จะอนุญาตให้เฉพาะ object ที่สืบทอดมาเท่านั้นที่เข้าถึงและใช้งานได้ ซึ่งจากลักษณะการใช้งานดังกล่าวนั้นเป็นผลดีสำหรับการเขียนโปรแกรมแบบ OOP นั้นเองซึ่งเป็นการบังคับว่าจะต้องสืบทอดจาก class แม่เท่านั้นจะมีสิทธิเข้าถึงและใช้งานได้ เรามาดูตัวอย่างโปรแกรม C# กันดีกว่า เริ่มแรกให้สร้าง Console Application แล้วตั้งชื่อว่า protected

จากนั้นแก้ไขไฟล์ Program.cs ตามนี้


using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace @protected

{

class A

{

protected int x = 123;

}

class B:A

{

public void ShowText()

{

B b = new B();

A a = new A();

//a.x = 66;

b.x = 55;

Console.WriteLine(b.x);

}

}

class Program

{

static void Main(string[] args)

{

B objectB = new B();

objectB.ShowText();

Console.ReadLine();

}

}

}

โปรแกรม c#

ผลลัพธ์การรันโปรแกรมจะเห็นว่า Object Class B ซึ่งสืบทอดมาจาก Class A สามารถเรียกใช้งานได้แต่ถ้าลองเอา comment //a.x = 66; โปรแกรมจะ error ซึ่ง Object Class A เองยังไม่สามารถเข้าถึงตัวแปร x ได้เพราะฉะนั้น protected นั้นมีไว้สำหรับ Class ที่สืบทอดเท่านั้น

โปรแกรม c#

Download Source Code

Tags: , , , , ,

Tags: Access Modifiers oop c# Protected ภาษา C เรียน c# โปรแกรม c#



Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>