码迷,mamicode.com
首页 > Windows程序 > 详细

浅谈C#中const、static readonly区别

时间:2015-07-03 19:06:46      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:

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只是保留了引用

 

浅谈C#中const、static readonly区别

标签:

原文地址:http://www.cnblogs.com/sakuya-GD/p/4619338.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!