const和static readonly 的区别

 偶然有机会 看到一份面试题目: const static readonly 在使用上面有什么不同?

Const是在编译的时候为其赋值,一旦赋值其值永远都不能改变。声明成const 类型的变量必须在声明的同时为其赋值,这样编译器在编译的时候就计算其具体“值”。正是因为这样的原因const类型的数据类型应该是简单数据类型或String类型。因为在引用类型中除了String类型外其它的引用类型都不能在编译的时候获取其准确值(null除外)。static readonly 是在运行时为其赋值,所以其类型可以是值类型也可以是引用类型。static readonly类型的变量只有两种途径为其赋值,在声明该变量的时候或在默认的静态构造函数里面为其赋值。实际上这两种方法最后生成的IL代码是相同的(都是在静态构造函数中赋值)。值得注意的是,当static readonly类型变量是引用类型时,在当前类中此变量虽然不能再进行new 操作分配空间,但是可以更改此变量内的field的值。

如下面代码:

 1 None.gif using  System;
 2 None.gif
 3 None.gif namespace  ConsoleApplication1
 4 ExpandedBlockStart.gifContractedBlock.gif dot.gif {
 5InBlock.gif    public class User
 6ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
 7InBlock.gif        
 8InBlock.gif        public string userName ;
 9InBlock.gif        public int userID;
10ExpandedSubBlockEnd.gif    }

11ExpandedSubBlockStart.gifContractedSubBlock.gif    /**//// <summary>
12InBlock.gif    /// Class1 的摘要说明。
13ExpandedSubBlockEnd.gif    /// </summary>

14InBlock.gif    class Class1
15ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
16InBlock.gif        public static readonly User user;
17InBlock.gif        public static readonly int i = 12;
18InBlock.gif        static Class1()
19ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
20InBlock.gif            user = new User();
21ExpandedSubBlockEnd.gif        }

22InBlock.gif        
23ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
24InBlock.gif        /// 应用程序的主入口点。
25ExpandedSubBlockEnd.gif        /// </summary>

26InBlock.gif        [STAThread]
27InBlock.gif        static void Main(string[] args)
28ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
29InBlock.gif            //
30InBlock.gif            // TODO: 在此处添加代码以启动应用程序
31InBlock.gif            //
32InBlock.gif            user.userName= "jjj";//这里是允许修改的
33InBlock.gif            user.userID = 13;
34InBlock.gif            Console.Write(user.userName);
35InBlock.gif            //user = new User(); 不能编译通过
36InBlock.gif            
37InBlock.gif            
38ExpandedSubBlockEnd.gif        }

39InBlock.gif        
40ExpandedSubBlockEnd.gif    }

41ExpandedBlockEnd.gif}

42 None.gif


如果把类User换成结构体的话,user.username = “jjj”这行就不能通过编译了。

<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

 

转载于:https://www.cnblogs.com/umlchina/archive/2005/05/19/159087.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值