[.Net Tips]Static

我们都知道静态变量属于类型之间共享的数据,但是自己也没有进去看看,近日有兴趣,写那些长篇大论似乎不在状态,时间紧迫,拿起static开始.

从代码开始

   1: using System;
   2: using System.Collections.Generic;
   3: using System.Linq;
   4: using System.Text;
   5:  
   6: namespace StaticInstance
   7: {
   8:     
   9:     class Program
  10:     {
  11:         static void Main(string[] args)
  12:         {
  13:             Test();
  14:             Console.Read();
  15:         }
  16:  
  17:         public static unsafe void Test()
  18:         {
  19:             fixed (char* address = BaseInstance.SharedVariable)
  20:             { 
  21:                 IntPtr i = new IntPtr(address);
  22:                 Console.WriteLine("The Address Of BaseInstance.SharedVariable: {0}", i);
  23:             }
  24:  
  25:             fixed (char* address = BaseInstance.SharedVariable)
  26:             {
  27:                 IntPtr i = new IntPtr(address);
  28:                 Console.WriteLine("The Address Of BaseInstance.SharedVariable 2: {0}", i);
  29:             }
  30:  
  31:             fixed (char* address = InstanceA.SharedVariable)
  32:             {
  33:                 IntPtr i = new IntPtr(address);
  34:                 Console.WriteLine("The Address Of InstanceA.SharedVariable: {0}", i);
  35:             }
  36:  
  37:             fixed (char* address = InstanceB.SharedVariable)
  38:             {
  39:                 IntPtr i = new IntPtr(address);
  40:                 Console.WriteLine("The Address Of InstanceB.SharedVariable: {0}", i);
  41:             }
  42:         }
  43:     }
  44:  
  45:     public class BaseInstance
  46:     {
  47:         public static string SharedVariable = "This is the SharedVariable";
  48:     }
  49:  
  50:     public class InstanceA : BaseInstance
  51:     { 
  52:         
  53:     }
  54:  
  55:     public class InstanceB : BaseInstance
  56:     { 
  57:     
  58:     }
  59: }

输出结果

image

可以看到各个类型之间共享了这一块内存。然而在原理上如何实现的呢?

小生斗胆猜测一下,日后有错再改了 :)

线索:

1. 在编译产生的元数据中存在.data区块,专门存放共享的数据

2. 类型在元数据中的布局指向的是元数据中的区块,在C++里ms我们可以这样表示

#program data_seg("BaseInstance")

       string SharedVariable = "This is the sharedVariable"

#program restore

参考: http://msdn.microsoft.com/en-us/library/h90dkhs0(VS.80).aspx

这样应用程序在执行时,会为元数据中的数据分配空间,而类型上所制定的引用则是指向这块共享区域里的空间. 而类之间关系的继承,则应该还是按照继承的原则全部COPY父类的布局

这样,也就只会共享一块内存了

 

而关于静态方法.下面是ECMA的描述

Static methods are methods that are associated with a type, not with its instances.

个人觉得和静态变量的实现类似,然而没有去看源代码,不敢乱下结论。

posted on 2008-10-30 00:50  xwang  阅读(270)  评论(0编辑  收藏  举报

导航