zoukankan      html  css  js  c++  java
  • C# const static readonly

    1 const 和 static readonly

    相同:通过类名而不是对象名进行访问,在程序中只读等等。在多数情况下可以混用。

    不同:const的值是在编译期间确定的,因此只能在声明时通过常量表达式指定其值。必须显示的初始化;

       而static readonly是在运行时计算出其值的,所以还可以通过静态构造函数来赋值。

    1). static readonly MyClass myins = new MyClass();

      不能换成const 因为new 调用构造函数,在运行时才确定

    2) static readonly int [] constIntArray = new int[] {1, 2, 3};

      不能换成const 因为new 调用构造函数,在运行时才确定

    2 const static readonly

    static 修饰的变量意味着它属于类级别,不需要实例化就可以直接通过 类名.变量名 来用。
    const 默认是 static 类型,因此属于类级别,它的特点是在编译的时候用const修饰的变量的值就已经是明确知道的定值,而不能是一个计算表达式。而且,只能在声明的时候给定它的值,以后都不可以改。
    readonly 不是static类型,属于实例级别,因此不能通过 类名.变量名 来用。只能通过 实例.变量名 来用。但是同const不同的是,它属于运行时的常量,也就是说,readonly可以在运行时才确定它的值,一旦确定以后也不可以更改(构造函数外)。需要注意的是:readonly的值可以在声明的时候指定,也可以自爱构造函数内部进行指定,其他地方均不可修改。

    3 所以

    public static const int a=1;

    语法错误

    可以是:public statc int a=1;

               public const int a=1;


  • 相关阅读:
    Java: Regular Expressions
    Java: Checked & Unchecked Exceptions
    二叉树的构建和层级打印
    [leetcode] 1032: Stream of Characters: Tries&AC自动机
    [leetcode] 1503: Previous Permutation With One Swap
    robot moving on the surface of a square
    killing rabbits
    Find the longest route with the smallest starting point
    [leetcode] Minimum Number of K Consecutive Bit Flips
    检测设备横屏 || 竖屏的状态
  • 原文地址:https://www.cnblogs.com/zjwei55/p/2135294.html
Copyright © 2011-2022 走看看