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

转载于:https://www.cnblogs.com/netbuy/articles/3531420.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值