C# 中有哪些不同的訪問修飾符?
訪問修飾符用於指定類成員或類本身型別的可訪問性範圍。共有六種不同的訪問修飾符。
公共 (Public)
私有 (Private)
受保護 (Protected)
內部 (Internal)
受保護內部 (Protected Internal)
私有受保護 (Private Protected)
公共訪問修飾符
實現公共訪問修飾符的物件可以在專案中的任何地方訪問,沒有任何限制。
示例
using System; namespace MyApplication{ public class Program{ public static void Main(){ Person person = new Person(); Console.WriteLine(person.Name); //Person Name is accessible as it is public } } public class Person{ public string Name = "Mark"; } }
私有訪問修飾符
實現私有訪問修飾符的物件只能在類或結構體內部訪問。因此,我們無法在建立它們的類外部訪問它們。
示例
using System; namespace MyApplication{ public class Program{ public static void Main(){ Person person = new Person(); Console.WriteLine(person.Name); //Since Name is private it is not accessible in Program class. // Error: Person.Name is inaccessible due to its protection level. } } public class Person{ private string Name = "Mark"; } }
受保護訪問修飾符
protected 關鍵字表示該物件可以在類內部以及所有從該類派生的類中訪問。
示例
using System; namespace MyApplication{ public class Program{ public static void Main(){ Employee employee = new Employee(); employee.Print(); //Output: Mark Person person = new Person(); Console.WriteLine(person.Name); // Error: Person.Name is inaccessible due to its protection level. } } public class Person{ protected string Name = "Mark"; } public class Employee : Person{ public void Print(){ Console.WriteLine(Name); } } }
內部訪問修飾符
對於 Internal 關鍵字,訪問僅限於當前專案程式集中定義的類。
示例
專案 1 −
using System; namespace MyApplication{ public class Program{ public static void Main(){ Person person = new Person(); Console.WriteLine(person.Name); //Output: Mark } } public class Person{ internal string Name = "Mark"; } }
輸出
Mark
專案 2 −
using MyApplication; using System; namespace Project2{ public class Project2Class{ public void Print(){ Person person = new Person(); Console.WriteLine(person.Name); // Error: Person.Name is inaccessible due to its protection level. } } }
受保護內部訪問修飾符 −
受保護內部訪問修飾符是 protected 和 internal 的組合。因此,我們只能在同一程式集中或其他程式集中派生類的類中訪問受保護內部成員。
示例
專案 1 −
using System; namespace MyApplication{ public class Program{ public static void Main(){ Person person = new Person(); Console.WriteLine(person.Name); //Output: Mark } } public class Person{ protected internal string Name = "Mark"; } }
輸出
Mark
專案 2 −
using MyApplication; using System; namespace Project2{ public class Project2Class : Person{ public void Print(){ Console.WriteLine(Name); //Output: Mark } } }
私有受保護訪問修飾符
私有受保護訪問修飾符是 private 和 protected 關鍵字的組合。我們可以在包含類內部或從包含類派生的類中訪問成員,但僅限於同一程式集(專案)。因此,如果我們嘗試從另一個程式集訪問它,我們將收到錯誤。此修飾符在 C# 7.2 及更高版本中有效。
廣告