惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

月光博客
月光博客
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
I
InfoQ
N
Netflix TechBlog - Medium
D
DataBreaches.Net
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
S
SegmentFault 最新的问题
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Hugging Face - Blog
Hugging Face - Blog
C
Cisco Blogs
T
Threat Research - Cisco Blogs
V
Visual Studio Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
博客园_首页
Recorded Future
Recorded Future
J
Java Code Geeks
The Cloudflare Blog
S
Securelist
人人都是产品经理
人人都是产品经理
T
Tor Project blog
云风的 BLOG
云风的 BLOG
The GitHub Blog
The GitHub Blog
V
Vulnerabilities – Threatpost
V
V2EX
P
Palo Alto Networks Blog
I
Intezer
罗磊的独立博客
博客园 - 叶小钗
T
The Exploit Database - CXSecurity.com
博客园 - 【当耐特】
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
The Hacker News
The Hacker News
T
The Blog of Author Tim Ferriss
Blog — PlanetScale
Blog — PlanetScale
P
Privacy International News Feed
P
Proofpoint News Feed
美团技术团队
Cisco Talos Blog
Cisco Talos Blog
博客园 - 司徒正美
Stack Overflow Blog
Stack Overflow Blog
L
LangChain Blog
L
LINUX DO - 热门话题
Simon Willison's Weblog
Simon Willison's Weblog
MyScale Blog
MyScale Blog
H
Help Net Security
W
WeLiveSecurity
Google Online Security Blog
Google Online Security Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com

博客园 - On the road....

c# -- 对象销毁和垃圾回收 C#集合 -- Equality和Order插件 C#集合--Dictionary C#集合 -- 自定义集合与代理 C#集合 -- Lists,Queues, Stacks 和 Sets C#集合--ICollection接口和IList接口 C#集合--数组 C#集合-列举(Enumeration) C#排序比较 Customer IEnuramble Extension C#相等性比较 c#列举和迭代器 C#记录对象的变化 C#按需序列化对象为Json字符串 C#如何更好地理解引用类型和值类型 C#代理那点事儿 Pro ASP.NET MVC –第五章 使用Razor Pro ASP.NET MVC –第六章 MVC的基本工具 Pro ASP.NET MVC –第四章 语言特性精华
c#如何区分静态只读变量和常量
On the road.... · 2014-02-19 · via 博客园 - On the road....

常量const

常量就是一个其值永远不会改变的静态字段。常量的值会在编译时自动推算,编译器会在遇到常量时,将其逐个替换为该常量的值。常量可以是C#内建的任何数字类型或枚举类型。声明一个常量的时候必须对其进行初始化。

例如:

class Program
{
    const int a = 2;        
    
    static void Main(string[] args)
    {           
        Console.WriteLine(a);
        Console.ReadLine();
    }
}

Const Sample

那么编译之后的IL的代码有两行值得注意:

1. const int a=2; 编译为.field private static literal int32 a = int32(0x00000002)

2. 在Console.WriteLine之前,常量的值被编译器推算出来:
IL_0001:  ldc.i4.2; 
IL_0002:  call       void [mscorlib]System.Console::WriteLine(int32)

静态只读static readonly

静态只读常量只是在某一个应用程序中初始化之后,不能对其进行修改。但是在不同的应用程序中可以有不同的值。

同样,对于上面的例子,如果我们把变量a更改为静态只读,那么IL代码有哪些变化呢?

1. static readonly int a=2;编译为.field private static initonly int32 a

2.在Console.WriteLine之前,不会推算其值:
IL_0001:  ldsfld     int32 Learning.LinqDemo.ConsoleApp.Program::a
IL_0006:  call       void [mscorlib]System.Console::WriteLine(int32)

两者的区别:

简单的一句话就可以:常量在所有的程序中都是同一个值,而静态只读变量在不同的程序中可以有不同的值。