日期:2014-05-17  浏览次数:20840 次

readonly 和 const 有啥区别?
public static readonly string 照片相似度低 = "";
const string 照片相似度低 = "";

是说 readonly  可以赋值,const 不能赋值吗?

------解决方案--------------------
const声明的是常量,其他的是变量。
------解决方案--------------------
readonly是运行时检查
const是编译时检查
------解决方案--------------------
        private static string _abc = "";
        public static readonly string abc
        {
            get
            {
                return _abc;
            }
        }
====================>
        const string abc

这样呢?应该直接点了吧
 
------解决方案--------------------
const 定义的常量经过编译后,在编译后的 DLL 当中已经不存在,直接被替换成数字或者字符串。优点是性能高。缺点是只能是基本类型数据。
readonly 定义的静态变量经过编译后,在 DLL 中依然是变量。优点是如果 A.exe 引用 B.dll 的 readonly 变量 C,当 C 的值发生变化,重新编译 B.dll 即可更新 C 的值,不必重新编译 A.exe。
------解决方案--------------------
最简单的例子

const int const_a=const_b*10
const int const_b=10;

因为编译器在编译时候已经确定好了值了,所以const_a是10*10=100

readonly int a=b*10;
readonly int b=10

这个运行时候才确定值,虽然你b=10,但还没运行到这里,所以b为默认滴0,此时a的值为0*10=0
------解决方案--------------------
看到楼主的问题,我也去搜了下。。而且自身实际体会了下。。它们分别有2点不同

1.const只能对值类型进行初始化赋值的操作,对于引用类型(string除外),初始化时只能赋值为NULL。。而readonly没这些限制

2.正如2楼所说的。。const是在编译时就已经解析了,然后对常量赋值了。。而readonly是在执行的时候才对常量进行赋值。。可能这么说不太容易明白,我刚看资料时在网上看到一段代码,贴你看看。。


using System;

class P
{

    static readonly int A=B*10;

    static readonly int B=10;   

    public static void Main(string[] args)

    {

        Console.WriteLine("A is {0},B is {1} ",A,B);

    }

}



using System;
class P
{
    const int A=B*10;
    const int B=10;&nbs