常量字段,只读字段、静态只读字段的使用

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

namespace ClassLibrary1
{
    public class Class1
    {
        /// <summary>
        /// 常量字段,必须给予初始值,否则编译器会提示错误
        /// </summary>
        public const double pi=3.14;

        public const string a = "";

        /// <summary>
        /// 静态只读字段必须在静态构造函数里面赋值
        /// </summary>
        public static readonly string aaaa = "";

        /// <summary>
        /// DateTime 不能用const修饰
        /// </summary>
        //public const DateTime dt = new DateTime();

        /// <summary>
        /// 只读字段,只能在构造函数内赋值,在构造函数外赋值会出现编译错误
        /// </summary>
        public readonly double pi2;

        /// <summary>
        /// 普通构造函数
        /// </summary>
        public Class1()
        {
            pi2 = 3.14;
           
        }

        /// <summary>
        /// 静态构造函数
        /// </summary>
        static Class1()
        {
            aaaa = "ssss";
        }
        /// <summary>
        /// 错误赋值方法
        /// </summary>
        //public void set()
        //{
        //    pi2 = 3.14;
        //}
    }

  
}

实例化class,首先会执行静态构造函数,再执行普通构造函数,静态类 public static class Class1 不能有普通构造函数!

posted @ 2014-08-22 13:47  feimon  阅读(355)  评论(0)    收藏  举报