点点滴滴访问量:
 

静态方法

C#的类中可以包含两种方法:静态方法和非静态方法。

使用了static 修饰符的方法为静态方法,反之则是非静态方法。

静态方法是一种 特殊的成员方法,它不属于类的某一个具体的实例,而是属于类本身。所以对静态方法不需要首先创建一个类的实例,而是采用类名.静态方法的格式

 

下面是一个使用静态方法的例子

using System;

 

namespace study1214

{

   

    class Class1

    {

   

 

        [STAThread]

        static void Main(string[] args)

        {

            int i = MyClass.Add(3,5);   //调用静态方法

            Console.WriteLine(i);

        }

 

    }

    class MyClass

    {

        public static int Add(int x,int y )

        {

            return x + y[zsp1] ;

        }

    }

}


 [zsp1]注意:静态方法中不能使用非静态成员,如class A

{

Int x ;

Static int y;

Static int F()

{

X=1; //错误,不允许访问非静态成员

Y=2; //正确

}

}

posted on 2006-04-12 16:34  sopper  阅读(310)  评论(0编辑  收藏  举报