浅谈C#中const、static readonly区别

const 编译时常量

static readonly 运行时常量

直接上代码

1.新建一个类库BLL->添加类Teacher

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace BLL
 8 {
 9    public  class Teacher
10     {
11         public static readonly int i = 3;
12         public static readonly string j = "static";
13 
14         public const int m = 6;
15         public const string n = "const";
16     }
17 }
View Code

2.新建空Web应用程序->添加Webform

/*页面HTML*/

 1 <html xmlns="http://www.w3.org/1999/xhtml">
 2 <head runat="server">
 3 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 4     <title></title>
 5 </head>
 6 <body>
 7     <form id="form1" runat="server">
 8     <div>
 9     <asp:TextBox ID="txti" runat="server"></asp:TextBox>
10     <asp:TextBox ID="txtj" runat="server"></asp:TextBox>
11     <asp:TextBox ID="txtm" runat="server"></asp:TextBox>
12     <asp:TextBox ID="txtn" runat="server"></asp:TextBox>
13     </div>
14     </form>
15 </body>
16 </html>
View Code

/*后台代码*/

 1 namespace WebApplication1
 2 {
 3     public partial class WebForm1 : System.Web.UI.Page
 4     {
 5         protected void Page_Load(object sender, EventArgs e)
 6         {
 7             Teacher t = new Teacher();
 8             this.txti.Text=Teacher.i.ToString();
 9             this.txtj.Text=Teacher.j.ToString();
10             this.txtm.Text = Teacher.m.ToString();
11             this.txtn.Text = Teacher.n.ToString();
12         }
13     }
14 }
View Code

 3.在IIS发布访问后(页面显示)

4.修改Teacher类中常量值

namespace BLL
{
   public  class Teacher
    {
        public static readonly int i = 5;
        public static readonly string j = "static_modify";

        public const int m = 9;
        public const string n = "const_modify";
    }
}
View Code

5.生成解决方案,替换发布包中的BLL.dll后访问页面结果发现

static变量修改成功了,而const变量修改失败...

 

结论 :const 会将值编译在代码中,而static只是保留了引用

 

posted @ 2015-07-03 18:16  sakuyaの  阅读(110)  评论(0编辑  收藏  举报