试验1

将下面的代码编译成一个程序集

using System;

namespace TestConst1
{
    
/// <summary>
    
/// Class1 的摘要说明。
    
/// </summary>
    public class Component
    {
        
//注意: c#不允许为常数指定static关键字
        
//因为常数隐含为static
        public const int MaxEntriesInList = 50;
    }

}

将下面的程序编译成另外一个程序集:

using System;
using TestConst1;

namespace TestConst2
{
    
/// <summary>
    
/// Class1 的摘要说明。
    
/// </summary>
    class App
    {
        
/// <summary>
        
/// 应用程序的主入口点。
        
/// </summary>
        [STAThread]
        
static void Main(string[] args)
        {
            Console.WriteLine(
"Max entries supported in list: " + Component.MaxEntriesInList );
            Console.ReadLine();
        }
    }
}

 

运行TestConst2.App程序,运行结果如下:

Max entries supported in list: 50

 

试验2

将第一个程序集改成:

using System;

namespace TestConst1
{
    
/// <summary>
    
/// Class1 的摘要说明。
    
/// </summary>
    public class Component
    {
        
//注意: c#不允许为常数指定static关键字
        
//因为常数隐含为static
        public const int MaxEntriesInList = 100;
    }

}

 

编译该程序集。

 

然后直接运行TestConst2.App,运行结果如下:

Max entries supported in list: 50

可以发现,运行结果没有变。

[]为什么没有变那?

[]这跟.net中对于常量的处理方法有关,当编译器编译代码的时候,遇见常量,就会用常量的值代替变量MaxEntriesInList,然后直接访问这个值,所以,访问常量是不需要内存的。这个时候,就是指示常量的那个变量的值发生了变化,也不会对已经编译好的程序集发生影响。

试验3

重新编译TestConst2.App,然后运行,结果如下:

Max entries supported in list: 100

 

 

试验4

将第一个程序集改成:

using System;

namespace TestConst1
{
    
/// <summary>
    
/// Class1 的摘要说明。
    
/// </summary>
    public class Component
    {
        
//注意: c#不允许为常数指定static关键字
        
//因为常数隐含为static
        public const int MaxEntriesInList = 500;
    }

}

 

不编译该程序集。

 

然后编译TestConst2.App,运行结果如下:

Max entries supported in list: 100

 

可以发现,运行结果没有变。

试验5

将第一个程序集改成:

using System;

namespace TestConst1
{
    
/// <summary>
    
/// Class1 的摘要说明。
    
/// </summary>
    public class Component
    {
        
//注意: c#不允许为常数指定static关键字
        
//因为常数隐含为static
        public const int MaxEntriesInList = 600;
    }

}

 

不编译该程序集。

但是将TestConst2的依赖项选中TestConst1

 

然后编译TestConst2.App,运行结果如下:

Max entries supported in list: 600

 

可以发现,运行结果发生了变化。而且在编译TestConst2的过程中,编译器先自动编译TestConst1,然后才编译TestConst2

相关文章:

  • 2022-01-04
  • 2021-08-21
  • 2022-02-26
  • 2021-07-29
  • 2022-02-21
  • 2021-05-12
  • 2021-06-24
  • 2022-12-23
猜你喜欢
  • 2021-07-11
  • 2022-12-23
  • 2021-08-03
  • 2022-01-14
  • 2021-08-19
  • 2021-11-27
  • 2022-12-23
相关资源
相似解决方案