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

適用於