C#类与变量作用域的测试例程

下面的例子说明一下类的成员的访问修饰符的用法
 

using System;
class Vehicle//定义汽车类
{
public int wheels; //公有成员轮子个数
protected float weight; //保护成员重量
public void F(){
wheels = 4;//正确允许访问自身成员
weight = 10; //正确允许访问自身成员
}
};
class train //定义火车类
{
public int num; //公有成员车厢数目
p rivate int passengers; //私有成员乘客数
p rivate float weight; //私有成员重量
public void F(){
num = 5; //正确允许访问自身成员
weight = 100; //正确允许访问自身成员
Vehicle v1 = new Vehicle();
v1.wheels = 4; //正确允许访问v1 的公有成员
//v1.weight = 6; 错误不允许访问v1 的保护成员可改为
weight = 6;
}
}
class Car:Vehicle //定义轿车类
{
int passengers; //私有成员乘客数
public void F(){
Vehicle v1 = new Vehicle();
V1.wheels = 4; //正确允许访问v1 的公有成员
V1.weight = 6; //正确允许访问v1 的保护成员
}
}
 

静态成员和非静态成员
若将类中的某个成员声明为static ,该成员称为静态成员。类中的成员要么是静态,要么是非静态的。一般说来静态成员是属于类所有的。非静态成员则属于类的实例——对象。
using System;
class Test
{
int x;
static int y;
void F() {
x = 1; // 正确,等价于this.x = 1
y = 1; // 正确,等价于Test.y = 1
}
static void G() {
x = 1; // 错误不能访问 this.x
y = 1; // 正确,等价于Test.y = 1
}
static void Main() {
Test t = new Test();
t.x = 1; // 正确
t.y = 1; // 错误不能在类的实例中访问静态成员
Test.x = 1; // 错误不能按类访问非静态成员
Test.y = 1; // 正确
}
}

原文地址:https://www.cnblogs.com/hackpig/p/1668453.html