ConditionalWeakTable<br>컴파일러가 대상 필드를 위탁 관리 대상에 동적으로 추가할 수 있도록 합니다.
작은 데모를 먼저 보십시오:
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
Conditional WeakTable
키를 유지하지 않습니다.즉, 키는 단지 집합된 구성원이기 때문에 활동 상태를 유지하지 않는다는 것이다
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.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.