当前位置:首页 > 通信资讯 > 正文

c# const readonly区别(const修饰函数)

1. 只有C#内置类型(int,double,long等)可以声明为const;结果、类和数组不能声明为const。

2. readonly 是在字段上使用的修饰符,直接以类名.字段访问。

3. const 必须在申明中初始化。之后不能再修改。

4. readonly可以在申明中初始化,也可以在构造函数中初始化,其它情况不能修改。

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 namespace const_and_readonly { class Program { static void Main(string[] args) { Console.WriteLine("Half a year have {0} Moths", Calendar.Moths/2); //直接类名.字段访问const字段 Calendar test1 = new Calendar(); Console.WriteLine("Every year has {0} weeks and {1} days", test1._weeks, test1._days);//readonly字段通过实例访问 Calendar test2 = new Calendar(31, 4); Console.WriteLine("January has {0} weeks and {1} days", test2._weeks ,test2 ._days); Console.ReadKey(); } } class Calendar { public const int Moths = 12; //const必须在声明中初始化 public readonly int _days=365; //readonly在声明中初始化 public readonly int _weeks; public Calendar() //readonly在构造函数内初始化 { _weeks = 52; } public Calendar(int days,int weeks) //readonly在构造函数内初始化 { _days = days; _weeks = weeks; } public void setvalue(int days,int weeks) { // _days = days; 无法对只读字段赋值 //_weeks = weeks; 无法对只读字段赋值 } }

以上所述是小编给大家介绍的C#中const 和 readonly 修饰符的用法详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!

原文链接:http://www.cnblogs.com/xiao9426926/archive/2016/09/18/5881382.html

如果您对该产品感兴趣,请填写办理(客服微信:xiaoxiongyidong)

为您推荐:

发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。