码迷,mamicode.com
首页 > 其他好文 > 详细

七问C#关键字const和readonly

时间:2014-07-16 22:54:43      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   strong   os   

const和readonly经常被用来修饰类的字段,两者有何异同呢?

 

  const

  1、声明const类型变量一定要赋初值吗?

--一定要赋初值

public class Student
    {
        public const int age;
    }

生成的时候,会报如下错:
bubuko.com,布布扣

 

正确的应该这样写:

public class Student
    {
        public const int age = 18;
    }

 

  2、声明const类型变量可以用static修饰吗?

--不可以

public class Student
    {
        public static const int age = 18;
    }

生成的时候,会报如下错:
bubuko.com,布布扣

 

正确的应该这样写:

public class Student
    {
        public const int age = 18;
    }

因为const默认是static。

 

  3、运行时变量可以赋值给const类型变量吗?

--不可以

public class Student
    {
        public const int age = 18;

        public Student(int a)
        {
            age = a + 1;
        }
    }

生成的时候,会报如下错:
bubuko.com,布布扣

 

const类型变量是编译期变量,无法把运行时变量赋值给编译期变量。

 

  4、const可以修饰引用类型变量吗?

--可以,但只能给引用类型变量赋null值。

public class Student
    {
        public const Teacher teacher = new Teacher();
    }

    public class Teacher
    {        
    }

生成的时候,会报如下错:
bubuko.com,布布扣


正确的应该这样写:

public class Student
    {
        public const Teacher teacher = null;
    }

    public class Teacher
    {        
    }

 

  readonly

  5、声明readonly类型变量一定要赋初值吗?

--不一定,既可以赋初值,也可以不赋初值。

以下不赋初值的写法正确:

public class Student
    {
        public readonly int age;
    }

以下赋初值的写法也对:

public class Student
    {
        public readonly int age = 18;
    }

 

  6、运行时变量可以赋值给readonly类型变量吗?  

--可以

以下在构造函数中给readonly类型变量赋值是可以的:

public class Student
    {
        public readonly int age = 18;

        public Student(int a)
        {
            age = a;
        }
    }

 

  7、声明readonly类型变量可以用static修饰吗?  

--可以的

以下写法正确:

public class Student
    {
        public static readonly int age = 18;
    }


 

  总结

const修饰符:
● 用const修饰的变量是编译期变量
● 不能把运行时变量赋值给const修饰的变量
● const修饰的变量在声明时要赋初值
● const修饰的变量不能在前面加static修饰
● cosnt也可以修饰引用类型变量,但一定要给引用类型变量赋null初值


readonly修饰符:   
● 用readonly修饰的变量是运行时变量
● 可以把运行时变量赋值给readonly修饰的变量
● readonly修饰的变量在声明时,既可以赋初值,也可以不赋初值
● readonly修饰的变量可以在前面加static修饰符

七问C#关键字const和readonly,布布扣,bubuko.com

七问C#关键字const和readonly

标签:style   blog   http   color   strong   os   

原文地址:http://www.cnblogs.com/darrenji/p/3835461.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!