| static为静态修饰符,可以放在对象前面(函数也是一种对象)如: class Example{
 public static void show(){
 Console.WriteLine("这是一个静态方法");
 }
 }
 可直接Example.show();去调用这个方法而不用实例化
 当然也可以定义静态的属性:
 public static string str="hello";
 但如果这样Example.str="helloworld";就出现问题了
 也就是客户端可以在任何地方去改变str的值。这样的话极容易产生错误,因为str的值是依靠Example类的,随时可以改变。比如再声明一个类:
 Class Class1
 {
 Example.str="helloworld";
 public void show()
 {
 Console.WriteLine(Example.str);//此时Example.str会输出helloworld
 }
 }
 class Example{
 public static string str="hello";
 }
 }
 要防止str值发生改变,就需要用到const修饰符
 public const string str="hello";//str被称为常量
 这是如果再对Example.str赋值,则编译器将产生错误
 用常量来保存公共数据是最为合适的。
 |