FixedAddressValueTypeAttribute 생성자

정의

FixedAddressValueTypeAttribute 클래스의 새 인스턴스를 초기화합니다.

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

예제

다음 예제에서는 특성을 사용하여 메모리에 FixedAddressValueTypeAttribute 정적 필드를 고정하는 방법을 보여 줍니다. 구조를 정의하고 형식AgeAge 정적 필드가 있는 두 클래스를 초기화합니다. 두 번째 클래스는 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

적용 대상