静态变量也称类变量,是在类的所有实例间共享;直接使用类名来引用;
静态方法通过类名触发!
C# code:
class Person
{
//属性开头字母大写,字段开头字母小写;
private string name;
public int Age { get; set; }
public string Sex { get; set; }
public string Profession{get ;set;}
//构造函数初始化!
public Person ()
{
name ="unkown";
}
public void SetName(string name)
{
this.name = name;
}
public void Sayhello()
{
//占位符:{0},{1}....
Console.WriteLine("大家好,我叫:{0},今年:{1},性别:{2},专业:{3}\n", this.name, this.Age, this.Sex, this.Profession);
}
public void Eating()
{
Console.WriteLine("{0}正在吃饭!\n", this.name);
}
public void Sleeping()
{
Console.WriteLine("{0}正在睡觉!\n", this.name);
}
public static void Working()//静态方法
{
Console.WriteLine("工作中!\n");
}
}
class StaticPerson
{
public static int StaticAge = 23; //静态变量,年龄=23;
public string color; //普通变量,颜色
public int GetStaticAger()
{
return StaticAge;
}
}
static void Main(string[] args)
{
//没有调用SetName(),默认调用构造函数,即名字为"unknown";
Person p = new Person();
p.Age = StaticPerson.StaticAge;
p.Sex = "男";
p.Profession = "计算机科学与技术";
p.Sayhello();
p.Eating();
Person.Working();//静态方法通过类名来引用;
//调用SetName();
Person p1 = new Person();
p1.SetName("steven");
p1.Age = StaticPerson.StaticAge;//静态变量在类的所有实例间共享
p1.Sex = "女";
p1.Profession = "英语";
p1.Sayhello();
p1.Sleeping();
int StaticAge = StaticPerson.StaticAge;//静态变量通过类名来引用;
Console.ReadKey();
}
}