标题: 在方法中,分为静态方法和非静态方法这时如何区分的? [打印本页] 作者: 庞海瑞 时间: 2013-8-6 19:38 标题: 在方法中,分为静态方法和非静态方法这时如何区分的? 在方法中,分为静态方法和非静态方法这时如何区分的?作者: 小天 时间: 2013-8-6 19:46
静态方法由static修饰,可以直接通过 类名.方法名() 调用,如
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 静态成员
{
class Program
{
static void Main(string[] args)
{
Person.age = 5;//静态成员的赋值
Console.WriteLine(Person.age);
Do();//由static修饰的方法不用new一个对象就可以使用
ConsoleHelp.ReadInt();//静态方法的调用
Console.ReadKey();
}
public static void Do()
{
Console.WriteLine("使用全局变量"+Person.age);
}
}
class Person
{
public static int age;//声明了一个全局变量(由static修饰)
public string name = "蜡笔小新";
//在非static方法中可以调用static成员
public void SayHello()
{
Console.WriteLine("我的名字叫{0},我今年{1}岁",name,age);
}
//在static方法中不能直接调用非static成员
public static void Speak()
{
// Console.WriteLine("我叫{0},今年{1}",name,age);
}