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/archive/2008/01/14/1037863.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值