const常量和static静态只读变量有何区别

/*--===------------------------------------------===---
作者:许明会
日期:2008年1月14日 9:59:52
目的:可以通过程序集引用const常量和static静态成员
--===------------------------------------------===---
*/

using System;

namespace xumh
{
    
public class runMyApp
    
{
        
static void Main()
        
{
            myClass test 
= new myClass();
            Console.WriteLine(
"半径为5.0的圆的面积为:{0}",test.CircleArea(5.0));
            Console.WriteLine(
"程序的当前版本是:{0}.",test.GetVersion());
            Console.WriteLine(
"public const double PI:{0}", myClass.VERSION );
            
//Console.WriteLine("", test.PI);
            Console.WriteLine("public static readonly string VERSION:{0}", myClass.PI);
        }

    }

}

/*--===------------------------------------------===---
半径为5.0的圆的面积为:78.5
程序的当前版本是:2.18.
public const double PI:2.18
public static readonly string VERSION:3.14
--===------------------------------------------===---
*/
/*--===------------------------------------------===---
作者:许明会
日期:2008年1月14日 8:54:48
目的:static变量和const变量有何区别?
环境:Windows Server 2003 + NetFramework3.5
编译方法:csc /t:library static.cs
--===------------------------------------------===---
*/

using System;

namespace xumh
{
    
public class myClass
    
{
        
public const double PI=3.14;
        
public double CircleArea(double r)
        
{
            
return PI*r*r;
        }


        
public static readonly string VERSION="2.18";
        
public string GetVersion()
        
{
            
return VERSION;
        }

    }

}

/*--===------------------------------------------===---
相同点:
常量符号属于类名,和static静态变量一样,通过类名引用。
不同点:
在方法的内部:const常量符号将直接用其值替代,static静态变量保留符号。

我的思考:既然const常量能保留符号,为什么在方法内却用常量值替代符号呢,难道是性能考虑;
反过来想,含有const常量的程序集修改后必然需要编译,
那么引用程序集的部分自然不用修改(不存在整站编译),而含有const的程序集的性能又提升了,倒是好事了。
--===------------------------------------------===---
*/
 
 




原文地址:https://www.cnblogs.com/flaaash/p/1037863.html