Share via


FixedAddressValueTypeAttribute 构造函数

定义

初始化 FixedAddressValueTypeAttribute 类的新实例。

public:
 FixedAddressValueTypeAttribute();
public FixedAddressValueTypeAttribute ();
Public Sub New ()

示例

以下示例演示如何使用 FixedAddressValueTypeAttribute 属性将静态字段固定到内存中。 它定义 一个 Age 结构,并初始化具有 类型 Age静态字段的两个类。 第二类适用于 FixedAddressValueTypeAttribute 固定字段的地址。 在实例化这两个对象并调用垃圾回收器之前和之后,会进行大量内存分配。 该示例的输出显示,尽管垃圾回收后第一个 Age 字段的地址已更改,但应用到的字段 FixedAddressValueTypeAttribute 的地址并未更改。

using System;
using System.Runtime.CompilerServices;

public struct Age {
   public int years;
   public int months;
}

public class FreeClass
{
   public static Age FreeAge;
   
   public static unsafe IntPtr AddressOfFreeAge()
   { 
      fixed (Age* pointer = &FreeAge) 
      { return (IntPtr) pointer; } 
   }
}

public class FixedClass
{
   [FixedAddressValueType]
   public static Age FixedAge;
   
   public static unsafe IntPtr AddressOfFixedAge()
   { 
      fixed (Age* pointer = &FixedAge) 
      { return (IntPtr) pointer; } 
   }   
}

public class Example
{
   public static void Main()
   {
      AllocateMemory();
      
      // Get addresses of static Age fields.
      IntPtr freePtr1 = FreeClass.AddressOfFreeAge();
      AllocateMemory();
      
      IntPtr fixedPtr1 = FixedClass.AddressOfFixedAge();
      AllocateMemory();

      // Garbage collection.
      GC.Collect();
      GC.WaitForPendingFinalizers();
      
      // Get addresses of static Age fields after garbage collection.
      IntPtr freePtr2 = FreeClass.AddressOfFreeAge();
      IntPtr fixedPtr2 = FixedClass.AddressOfFixedAge();
        
      // Display addresses before and after garbage collection
      Console.WriteLine("Normal static: {0} -> {1}", freePtr1, freePtr2);
      Console.WriteLine("Pinned static:  {0} -> {1}", fixedPtr1, fixedPtr2);  
   }

   // Allocate memory for 100,000 objects.
   static public void AllocateMemory()
   {
      for (int ctr = 0; ctr <= 100000; ctr++)
      {
         object o = new object();      
      }
   }
}
// The example displays output similar to the following:
//       Normal static: 19932420 -> 19863704
//       Pinned static:  19985508 -> 19985508

适用于