C#中的const和readonly关键字详解

2022-08-04,,,

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

const

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

一定要赋初值

public class student
{
    public const int age;
}

生成的时候,会报如下错:

正确的应该这样写:

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

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

不可以

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

生成的时候,会报如下错:

正确的应该这样写:

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;
        }
    }

生成的时候,会报如下错:

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

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

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

    public class student
    {
        public const teacher teacher = new teacher();
    }

    public class teacher
    {        
    }

生成的时候,会报如下错:

正确的应该这样写:

    public class student
    {
        public const teacher teacher = null;
    }

    public class teacher
    {        
    }

readonly

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

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

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

    public class student
    {
        public readonly int age;
    }

以下赋初值的写法也对:

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

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

可以

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

    public class student
    {
        public readonly int age = 18;

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

3、声明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的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持。

《C#中的const和readonly关键字详解.doc》

下载本文的Word格式文档,以方便收藏与打印。