本文整理汇总了C#中ConditionalWeakTable.GetOrCreateValue方法的典型用法代码示例。如果您正苦于以下问题:C# ConditionalWeakTable.GetOrCreateValue方法的具体用法?C# ConditionalWeakTable.GetOrCreateValue怎么用?C# ConditionalWeakTable.GetOrCreateValue使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ConditionalWeakTable
的用法示例。
在下文中一共展示了ConditionalWeakTable.GetOrCreateValue方法的3个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetOrCreateValue
public void GetOrCreateValue () {
var cwt = new ConditionalWeakTable <object,object> ();
try {
cwt.GetOrCreateValue (null);
Assert.Fail ("#0");
} catch (ArgumentNullException) {}
object key = "foo";
object val = cwt.GetOrCreateValue (key);
Assert.IsTrue (val != null, "#2");
Assert.AreEqual (typeof (object), val.GetType () , "#3");
Assert.AreEqual (val, cwt.GetOrCreateValue (key), "#4");
var cwt2 = new ConditionalWeakTable <object, string> ();
try {
cwt2.GetOrCreateValue (key);
Assert.Fail ("#5");
} catch (MissingMethodException) {}
}
示例2: GetValueTest
public static void GetValueTest()
{
ConditionalWeakTable<object, object> cwt = new ConditionalWeakTable<object, object>();
object key = new object();
object obj = null;
object value = cwt.GetValue(key, k => new object());
Assert.True(cwt.TryGetValue(key, out value));
Assert.Equal(value, cwt.GetOrCreateValue(key));
WeakReference<object> wrValue = new WeakReference<object>(value, false);
WeakReference<object> wrkey = new WeakReference<object>(key, false);
key = null;
value = null;
GC.Collect();
// key and value must be collected
Assert.False(wrValue.TryGetTarget(out obj));
Assert.False(wrkey.TryGetTarget(out obj));
}
示例3: Add
public static void Add(int numObjects)
{
// Isolated to ensure we drop all references even in debug builds where lifetime is extended by the JIT to the end of the method
Func<int, Tuple<ConditionalWeakTable<object, object>, WeakReference[], WeakReference[]>> body = count =>
{
object[] keys = Enumerable.Range(0, count).Select(_ => new object()).ToArray();
object[] values = Enumerable.Range(0, count).Select(_ => new object()).ToArray();
var cwt = new ConditionalWeakTable<object, object>();
for (int i = 0; i < count; i++)
{
cwt.Add(keys[i], values[i]);
}
for (int i = 0; i < count; i++)
{
object value;
Assert.True(cwt.TryGetValue(keys[i], out value));
Assert.Same(values[i], value);
Assert.Same(value, cwt.GetOrCreateValue(keys[i]));
Assert.Same(value, cwt.GetValue(keys[i], _ => new object()));
}
return Tuple.Create(cwt, keys.Select(k => new WeakReference(k)).ToArray(), values.Select(v => new WeakReference(v)).ToArray());
};
Tuple<ConditionalWeakTable<object, object>, WeakReference[], WeakReference[]> result = body(numObjects);
GC.Collect();
Assert.NotNull(result.Item1);
for (int i = 0; i < numObjects; i++)
{
Assert.False(result.Item2[i].IsAlive, $"Expected not to find key #{i}");
Assert.False(result.Item3[i].IsAlive, $"Expected not to find value #{i}");
}
}