const修饰的常量是静态常量,而readonly是动态常量。他们的区别可以从静态常量和动态常量的特性来说明:
- const修饰的常量在声明时必须初始化值;readonly修饰的常量可以不初始化值,且可以延迟到构造函数。
- cons修饰的常量在编译期间会被解析,并将常量的值替换成初始化的值;而readonly延迟到运行的时候。
- const修饰的常量注重的是效率;readonly修饰的常量注重灵活。
- const修饰的常量没有内存消耗;readonly因为需要保存常量,所以有内存消耗。
- const只能修饰基元类型、枚举类、或者字符串类型;readonly却没有这个限制。
1. 如果我们在const修饰的常量前加static的话,会提示错误,因为const编译后就是static常量了。(PM:如果不编译的话,编辑器不会报错。编译后,再提示错误! )
2. readonly修饰的在构造函数中被赋值后就不可以改变。
3. readonly是动态常量,在编译期间是不会解析的,所以开始就是默认值, A和B都是int类型,值都是0,所以A=0*10=0,程序接着执行到B=10,才会真正的B的初值10赋给B。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
class Person
{
//const修饰的常量默认为static常量
public const int myConstInt = 10;
public readonly string name;
public Person(string name)
{
this.name = name;
}
}
public class TestDataStruct : MonoBehaviour {
static readonly int A = B * 10;
static readonly int B = 10;
// Use this for initialization
void Start () {
//溢出产生编译时错误或导致引发 System.OverflowException
//checked
//{
// int a = 999999999;
// //a *= 66666;
//}
Debug.Log("A = " + A);
Debug.Log("B = " + B);
Person p = new Person("Jack");
//p.name = "Marry";
Debug.Log("p.name = " + p.name);
Debug.Log("myConstInt = " + Person.myConstInt);
}
// Update is called once per frame
void Update () {
}
}