赞
踩
在C#中,可访问级别(access modifiers
)用于控制类、字段、方法和属性等成员的可访问性。C#
提供了几种可访问级别,它们决定了哪些代码可以访问特定成员。
以下是C#中最常见的可访问级别:
public
:公共访问级别允许成员在程序的任何地方访问。private
:私有访问级别限制成员只能在定义它们的类或结构体内部访问。protected
:受保护的访问级别允许成员在定义它们的类或结构体以及派生类中访问。internal
:内部访问级别允许成员在同一程序集中的任何位置访问。protected internal
:受保护的内部访问级别允许成员在同一程序集中的任何位置以及派生类中访问。
示例代码:
using System; public class Example { public int publicField; // 公共字段 private int privateField; // 私有字段 protected int protectedField; // 受保护字段 internal int internalField; // 内部字段 protected internal int protectedInternalField; // 受保护的内部字段 // 公共方法 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."); } // 内部方法 internal void InternalMethod() { Console.WriteLine("This is an internal method."); } // 受保护的内部方法 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; // 可以访问内部字段 Console.WriteLine("Accessing internal field: " + example.internalField); example.protectedInternalField = 25; // 可以访问受保护的内部字段 Console.WriteLine("Accessing protected internal field: " + example.protectedInternalField); example.PublicMethod(); // 可以调用公共方法 // 无法调用私有方法 // example.PrivateMethod(); // 编译错误 // 无法调用受保护方法 // example.ProtectedMethod(); // 编译错误 example.InternalMethod(); // 可以调用内部方法 example.ProtectedInternalMethod(); // 可以调用受保护的内部方法 Derived derived = new Derived(); derived.AccessProtectedField(); // 可以在派生类中访问受保护字段 } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。