好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

C#中const 和 readonly 修饰符的用法详解

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

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

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

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

?

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://HdhCmsTestcnblogs测试数据/xiao9426926/archive/2016/09/18/5881382.html

dy("nrwz");

查看更多关于C#中const 和 readonly 修饰符的用法详解的详细内容...

  阅读:46次