ConditionalWeakTable<br>컴파일러가 대상 필드를 위탁 관리 대상에 동적으로 추가할 수 있도록 합니다.

6152 단어
MSDN 소개:https://msdn.microsoft.com/zh-cn/library/dd287757(v=vs.100).aspx
작은 데모를 먼저 보십시오:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
using System.Runtime.CompilerServices;
 
namespace ExtensionProps
{
    public class Person
    {
 
    }

    public class SomeClass
    {
 
    }

    public class ExtraPersonProps
    {
        public int Age { get; private set; }
        public string Name { get; private set; }
 

        public ExtraPersonProps(int age, string name)
        {
            Age = age;
            Name = name;
        }
    }
 
    class Program
    {
        static void Main(string[] args)
        { 
            Console.WriteLine("=========Using Fixed Data==========\r
"); //demo with fixed data ConditionalWeakTable<Person, ExtraPersonProps> cwtPerson = new ConditionalWeakTable<Person, ExtraPersonProps>(); Person p = new Person(); cwtPerson.Add(p, new ExtraPersonProps(1,"demoPerson")); ExtraPersonProps props; if (cwtPerson.TryGetValue(p, out props)) Console.WriteLine(string.Format("value of Person is : Age {0}, Name: {1}", props.Age, props.Name)); Console.WriteLine("=========Using Dictionary==========\r
"); //demo with Dictonary data ConditionalWeakTable<Person, Dictionary<string, object>> cwtPerson2 = new ConditionalWeakTable<Person, Dictionary<string, object>>(); Person p2 = new Person(); Dictionary<string, object> data = new Dictionary<string, object>(); data.Add("age", 2); data.Add("name", "demoPerson2"); cwtPerson2.Add(p2, data); Dictionary<string, object> dataRetrieved; if (cwtPerson2.TryGetValue(p2, out dataRetrieved)) Console.WriteLine(string.Format("value of Person is : Age {0}, Name: {1}", dataRetrieved["age"], dataRetrieved["name"])); Console.ReadLine(); } } }

Which outputs this
=========Using Fixed Data==========
value of Person is : Age 1, Name: demoPerson
=========Using Dictionary==========
value of Person is : Age 2, Name: demoPerson2
몇 가지 주의해야 할 점이 있다.
ConditionalWeakTable 클래스를 사용하면 언어 컴파일러가 런타임 시 관리되는 객체에 임의의 속성을 추가할 수 있습니다.Conditional WeakTable 대상은 키로 표시된 위탁 관리 대상을 값으로 표시된 추가 속성에 귀속시키는 사전입니다.객체의 키는 TKey 클래스의 개체 인스턴스이며 해당 클래스에 속성이 첨부되고 해당 객체에 할당된 속성 값입니다.
키는 유일해야 함;다시 말하면, Conditional WeakTable 클래스는 모든 위탁 관리 대상의 추가 값을 지원한다.두 키가 Object에 전달된 경우Reference Equals 메서드는 같은 키로 true를 반환합니다.
Conditional WeakTable 클래스 저장 키/값 쌍의 집합에도 불구하고 사전 대상이 아닌 표로 보는 것이 좋습니다.ConditionalWeakTable 클래스는 사전과 여러 가지 측면에서 다릅니다.
키를 유지하지 않습니다.즉, 키는 단지 집합된 구성원이기 때문에 활동 상태를 유지하지 않는다는 것이다
GetEnumerator 또는 Contains와 같은 사전에서 일반적으로 사용되는 모든 메서드는 포함할 수 없습니다
IDictionary 인터페이스가 구현되지 않았습니다
using System;
using System.Runtime.CompilerServices;

public class Example
{
   public static void Main()
   {
      var mc1 = new ManagedClass();
      var mc2 = new ManagedClass();
      var mc3 = new ManagedClass();

      var cwt = new ConditionalWeakTable<ManagedClass, ClassData>();
      cwt.Add(mc1, new ClassData());          
      cwt.Add(mc2, new ClassData());
      cwt.Add(mc3, new ClassData());

      var wr2 = new WeakReference(mc2);
      mc2 = null;

      GC.Collect();

      ClassData data = null; 

      if (wr2.Target == null)
          Console.WriteLine("No strong reference to mc2 exists.");   
      else if (cwt.TryGetValue(mc2, out data))
          Console.WriteLine("Data created at {0}", data.CreationTime);      
      else
          Console.WriteLine("mc2 not found in the table.");
   }
}

public class ManagedClass
{ 
}

public class ClassData
{
   public DateTime CreationTime;
   public object Data;   

   public ClassData()
   {
      CreationTime = DateTime.Now;
      this.Data  = new object();     
   }
}
// The example displays the following output:
//       No strong reference to mc2 exists.
using System;
using System.Runtime.CompilerServices;
using System.Threading;

public class ManagedObject
{
}

public class AttachedProperty
{
   public AttachedProperty(ManagedObject obj, int ctr)
   {
      this.obj = obj;
      this.ctr = ctr;
   }

   public int ctr;
   public ManagedObject obj; 
}

public class Example
{
   public static void Main()
   {
      // Create two managed objects.
      ManagedObject m1 = new ManagedObject();
      ManagedObject m2 = new ManagedObject();

      // Define their attached property values.
      AttachedProperty p1 = new AttachedProperty(null, 0);
      AttachedProperty p2 = new AttachedProperty(m1, 1);

      // Create the table and add the key/value pairs.
      var table = new ConditionalWeakTable<ManagedObject, AttachedProperty>();
      table.Add(m1, p1);
      table.Add(m2, p2);

      // Destroy m1.
      m1 = null;
      // Sleep for 1 second to allow m1 to be garbage collected.
      Thread.Sleep(1000);
      // Reinstantiate m1
      m1 = new ManagedObject();

      // Try to retrieve m1 and m2.
      AttachedProperty value = null;   
      if (table.TryGetValue(m2, out value))
         Console.WriteLine("m2: ({0}, {1})", value.obj, value.ctr);
      else
         Console.WriteLine("m2 is not in the table.");

      if (table.TryGetValue(m1, out value))
         Console.WriteLine("m1: ({0}, {1})", value.obj, value.ctr);
      else
         Console.WriteLine("m1 is not in the table.");
   }
}
// The example displays the following output:
//       m2: (ManagedObject, 1)
//       m1 is not in the table.

좋은 웹페이지 즐겨찾기