c#学习5,静态字段,静态函数,静态类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 静态成员
{
class Program
{
static void Main(string[] args)
{
person.TotalCount=30;//全局变量即静态变量,不需要new一个对象
Console.WriteLine(person.TotalCount);
doit();
person.renren();//可以不用new一个对象
person p1 = new person();
p1.age = 200;
p1.报告();
Console.ReadKey();
}
public static void doit()
{
Console.WriteLine("fff");
Console.WriteLine("使用全局变量:" + person.TotalCount);
}
}
//静态类不能被new成一个对象的
public class person//类名前加一个public
{
public static int TotalCount;//字段,static 与具体事例无关
public int age;
public static void renren()
{
Console.WriteLine("zongshu:{0}" , TotalCount);//不能使用非static函数
// Console.WriteLine("zongshu:{0}" + TotalCount+"总年龄:"+age);//static函数不能调用非static函数
}
public void 报告()
{
Console.WriteLine("总年龄:" + age+"总人数"+TotalCount);//在非static中可以调用static
}

}
}

//静态类的实例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 静态类
{
class Program
{
static void Main(string[] args)
{
// consolehelper h1 = new consolehelper();//这是错误的,静态类不能用new来实例化,一般用来实现一些存的函数库

consolehelper.ReadInt();
Console.ReadKey();
}
}
static class consolehelper
{
public static int ReadInt()
{
string str = Console.ReadLine();
return Convert.ToInt32(str);
}

}
}

原文地址:https://www.cnblogs.com/cyychenyijie/p/3731810.html