using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 静态成员
{
class Program
{
static void Main(string[] args)
{
Person.TotalCount = 30;//用了ststic可以直接使用该静态成员
Person k1 = new Person();//没有static 必须new一个对象才能访问
k1.Age= 10;
Console.WriteLine(Person.TotalCount);
DoIt();//调用DoIt方法
Dog m1= new Dog();//非static,所以new一个对象
m1.叫唤();//调用叫唤方法
Person.人口回报();//输出方法
Person n1 = new Person();
n1.Age = 300;
n1.SayHello();
ConsoleHelper.ReadInt();//静态类不能被new实例化,直接调用静态类方法即可
Console.ReadKey();
}
public static void DoIt()//方法
{
Console.WriteLine("ggg");
Console.WriteLine("使用全局变量是:{0}", Person.TotalCount);
}
}
class Person
{
public static int TotalCount;//静态成员,可以当成全局变量使用
public int Age;//非静态成员
public static void 人口回报()//方法后不用加;
{
Console.WriteLine("总人口:{0}", TotalCount);//在static成员中不能直接调用非static成员,Age在class Person中定义的是非static的
}
public void SayHello()
{
Console.WriteLine("我的年龄是{0},全球人口是{1}", Age, TotalCount);//因为是void 是非ststic 所以可以输出static的TotalCount
//和非static的Age,而非static的输出要new对象才可以。
}
}
public class Dog
{
public void 叫唤()//方法
{
Console.WriteLine("旺旺:{0}",Person.TotalCount);
}
}
static class ConsoleHelper //定义静态类
{
public static int ReadInt()//静态类方法
{
string str = Console.ReadLine();
return Convert.ToInt32(str);
}
}
}
WF静态成员4
最新推荐文章于 2021-02-27 13:22:26 发布