类中的成员要么是静态的要么是非静态的。
一般来说,静态成员都归属于类所有,使用static关键字来声明,不能在类的实例中访问静态成员;非静态成员属于类的实例——对象所有,不能按照类访问静态成员来访问。
下面用一个实例来帮助理解:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test
{
class Test
{
int x; //非静态成员,属于实例所有
static int y; //静态成员,属于类所有
void F() //给x,y赋值
{
x = 1;
y = 1;
}
static void G() //取返回值
{
x = 1; //错误,实质为this.x=1,不能访问this.x
y = 1; //正确
}
static void main()
{
Test t = new Test(); //创建和初始化类的实例
t.x = 1; //正确
t.y = 1; //错误,不能在类的实例中访问静态成员
Test.x = 1; //错误,不能按类访问静态成员
Test.y = 1;
}
}
}
我们在C#编程时,关于静态成员和非静态成员是经常遇到的问题,所以从开始就要理解清楚,以后才能轻装上路。