C#-const和readonly

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 () {
		
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值