C#可訪問級別Public,private,protected,internal
在C#中,可訪問級別(access modifiers
)用于控制類、字段、方法和屬性等成員的可訪問性。C#
提供了幾種可訪問級別,它們決定了哪些代碼可以訪問特定成員。
以下是C#中最常見的可訪問級別:
public
:公共訪問級別允許成員在程序的任何地方訪問。private
:私有訪問級別限制成員只能在定義它們的類或結(jié)構(gòu)體內(nèi)部訪問。protected
:受保護的訪問級別允許成員在定義它們的類或結(jié)構(gòu)體以及派生類中訪問。internal
:內(nèi)部訪問級別允許成員在同一程序集中的任何位置訪問。protected internal
:受保護的內(nèi)部訪問級別允許成員在同一程序集中的任何位置以及派生類中訪問。
示例代碼:
using System; public class Example { public int publicField; // 公共字段 private int privateField; // 私有字段 protected int protectedField; // 受保護字段 internal int internalField; // 內(nèi)部字段 protected internal int protectedInternalField; // 受保護的內(nèi)部字段 // 公共方法 public void PublicMethod() { Console.WriteLine("This is a public method."); } // 私有方法 private void PrivateMethod() { Console.WriteLine("This is a private method."); } // 受保護方法 protected void ProtectedMethod() { Console.WriteLine("This is a protected method."); } // 內(nèi)部方法 internal void InternalMethod() { Console.WriteLine("This is an internal method."); } // 受保護的內(nèi)部方法 protected internal void ProtectedInternalMethod() { Console.WriteLine("This is a protected internal method."); } } public class Derived : Example { public void AccessProtectedField() { // 在派生類中可以訪問受保護字段 protectedField = 10; Console.WriteLine("Accessing protected field from derived class: " + protectedField); } } class Program { static void Main(string[] args) { Example example = new Example(); example.publicField = 5; // 可以訪問公共字段 Console.WriteLine("Accessing public field: " + example.publicField); // 無法訪問私有字段 // example.privateField = 10; // 編譯錯誤 // 無法訪問受保護字段 // example.protectedField = 15; // 編譯錯誤 example.internalField = 20; // 可以訪問內(nèi)部字段 Console.WriteLine("Accessing internal field: " + example.internalField); example.protectedInternalField = 25; // 可以訪問受保護的內(nèi)部字段 Console.WriteLine("Accessing protected internal field: " + example.protectedInternalField); example.PublicMethod(); // 可以調(diào)用公共方法 // 無法調(diào)用私有方法 // example.PrivateMethod(); // 編譯錯誤 // 無法調(diào)用受保護方法 // example.ProtectedMethod(); // 編譯錯誤 example.InternalMethod(); // 可以調(diào)用內(nèi)部方法 example.ProtectedInternalMethod(); // 可以調(diào)用受保護的內(nèi)部方法 Derived derived = new Derived(); derived.AccessProtectedField(); // 可以在派生類中訪問受保護字段 } }
到此這篇關(guān)于C#可訪問級別Public,private,protected,internal的文章就介紹到這了,更多相關(guān)C#可訪問級別內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Unity3D UI Text得分數(shù)字增加的實例代碼
這篇文章主要介紹了Unity3D UI Text得分數(shù)字增加方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-04-04c# HttpWebRequest通過代理服務(wù)器抓取網(wǎng)頁內(nèi)容應(yīng)用介紹
在C#項目開發(fā)過程中可能會有些特殊的需求比如:用HttpWebRequest通過代理服務(wù)器驗證后抓取網(wǎng)頁內(nèi)容,要想實現(xiàn)此方法并不容易,本文整理了一下,有需求的朋友可以參考下2012-11-11