C# 中 public、protected 和 private 访问限定符之间有什么区别?
Public 访问限定符
public 访问限定符允许类将它的成员变量和成员函数公之于众,可被其他函数和对象访问。任何 public 成员都可以在类外被访问。
示例
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
Protected 访问限定符
protected 访问限定符允许子类访问其父类的成员变量和成员函数。
让我们看一个受保护访问限定符的示例,该示例访问 protected 成员。
示例
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
Private 访问限定符
private 访问限定符允许类将它的成员变量和成员函数隐藏起来,不对其他函数和对象开放。只有该类的函数才能访问它的 private 成员。即使该类的实例也不能访问其 private 成员。
示例
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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP