静态函数的访问修饰符的问题

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

namespace staticTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Bird.showBird();
            Bird bird1= Bird.CreateBird();
            Console.WriteLine("占内存为" + bird1.GetHashCode());
            Bird bird2 = Bird.CreateBird();
            Console.WriteLine("占内存为" + bird2.GetHashCode());

            Console.ReadLine();
        }
       
    }
    class Bird
    {
        static Bird() //静态构造函数前面不允许有访问修饰符
        {
            Console.WriteLine("静态构造方法创建");

        }
        public static void showBird()
        {
            Console.WriteLine("一只小鸟诞生了");
        }
        private static Bird onebird;
        public static Bird CreateBird()
        {
            if (onebird == null)
            {
                onebird = new Bird();
            }
            return onebird;
        }
    }
}

Bird 这个类中有个静态构造函数,前面不能加任何的访问修饰符 public private protected 都是不可以的
而 Main 这个函数就可以加任何的访问修饰符
本例运行后在Main 函数中调用Bird类的CreateBird() 方法来访问Bird类中的私有字段。这里并没有调用构造函数来创建对象,用了一个Bird类型的变量。
运行结果会发现两个对象是引用的一个内存地址,因为有个判断~

posted @ 2008-06-03 17:34  坤哥  阅读(590)  评论(0编辑  收藏  举报