Const compile-time constants
Static readonly run-time constant
Directly on the code
1. Create a new Class library bll-> Add Class teacher
1 usingSystem;2 usingSystem.Collections.Generic;3 usingSystem.Linq;4 usingSystem.Text;5 usingSystem.Threading.Tasks;6 7 namespaceBLL8 {9 Public classTeacherTen { One Public Static ReadOnly inti =3; A Public Static ReadOnly stringj ="Static"; - - Public Const intm =6; the Public Const stringn ="Const"; - } -}View Code
2. Create a new empty Web application, add WebForm
/* Page html*/
1"http://www.w3.org/1999/xhtml">2"Server">3<meta http-equiv="Content-type"Content="text/html; Charset=utf-8"/>4<title></title>56<body>7<form id="Form1"runat="Server">8<div>9<asp:textbox id="Txti"runat="Server"></asp:TextBox>Ten<asp:textbox id="TXTJ"runat="Server"></asp:TextBox> One<asp:textbox id="Txtm"runat="Server"></asp:TextBox> A<asp:textbox id="Txtn"runat="Server"></asp:TextBox> -</div> -</form> the</body> -View Code/* Background Code */
1 namespaceWebApplication12 {3 Public Partial classWebForm1:System.Web.UI.Page4 {5 protected voidPage_Load (Objectsender, EventArgs e)6 {7Teacher T =NewTeacher ();8 This. Txti. text=teacher.i.tostring ();9 This. Txtj. text=teacher.j.tostring ();Ten This. Txtm. Text =teacher.m.tostring (); One This. Txtn. Text =teacher.n.tostring (); A } - } -}View Code
3. After the IIS publishing access (page display)
4. Modifying constant values in the teacher class
namespacebll{ Public classTeacher { Public Static ReadOnly inti =5; Public Static ReadOnly stringj ="static_modify"; Public Const intm =9; Public Const stringn ="const_modify"; }}View Code5. Build the solution, replace the BLL.dll in the publish package after accessing the page results found
The static variable modification succeeded, and the const variable modification failed ...
Conclusion: const will have the value in the code, and static just keeps the reference
On the difference between const and static readonly in C #