Net复习笔记:第七部分:Const和Readonly静态常量和静态字段

  1. 静态常量Const(常量),动态常量,readonly(只读)
  2. 常量在定义时必须初始化
  3. 不能用new初始化常量,因为常量的值在编译期就必须确定,而new是在运行期才确定的
  4. Readonly不能用作局部变量,const可以用作字段和局部变量

通过程序得到结论

public partial class WebForm9 : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {

            UserInfo usif = new UserInfo();

            Response.Write(UserInfo.Name+"<br>");

            Response.Write(UserInfo.Passw + "<br>");

 

            Response.Write(usif.Age + "<br>");

            Response.Write(usif.Sex + "<br>");

 

            UserInfo usif1 = new UserInfo(66, "zzl");

            Response.Write(usif1.Age + "<br>");

            Response.Write(usif1.Sex + "<br>");

        }

    }

    class UserInfo

    {

        public const string Name = "elong";

        public readonly int Age = 22;

        public readonly string Sex;

        public static readonly string Passw = "00111";

        public UserInfo()

        {

            Age = 23;

          

        }

 

        public UserInfo(int age, string sex)

        {

            Age = age;

            Sex = sex;

        }

 

        static UserInfo()

        {

            Passw = "123456";

        }

 

        public string InlineConst()

        {

            const string myna = "tuan";

            return myna;

        }

    }

  1. const必须在声明的时候指定初始化值
  2. readonly和static readonly可以在初始化的时候指定值,也可以在构造函数里面指定值,而且static readonly必须在静态构造函数内指定值static UserInfo() {Passw = "123456"; }
  3. const和static readonly定义的常量是静态的,只能有类直接访问,而readonly定义的是非静态的只能有类的实例访问
  4. const可以定义字段也可以定义局部变量,而readonly只能定义字段不能定义局部变量,所以readonly可以称作是只读字段
  5. const(默认就静态的,不能和static同时使用)不能再构造函数内初始化,而readonly可以在构造函数内初始化,但是static readonly必须在静态构造函数内指定值static UserInfo() {Passw = "123456"; }
  6. const只能是编译期可以识别的基元类型,例如int char  string 而readonly可以是任何类型
  7. 构造函数初始化是在运行期
  8. 数组和结构体不能声明为 const
posted @ 2014-01-23 16:46  瀚海行舟  阅读(99)  评论(0编辑  收藏  举报