I\'d like to create a Dictionary object, with string Keys, holding values which are of a generic type. I imagine that it would look something like this:
Dict
I came to a type safe implementation using ConditionalWeakTable.
public class FieldByType
{
static class Storage
where T : class
{
static readonly ConditionalWeakTable table = new ConditionalWeakTable();
public static T GetValue(FieldByType fieldByType)
{
table.TryGetValue(fieldByType, out var result);
return result;
}
public static void SetValue(FieldByType fieldByType, T value)
{
table.Remove(fieldByType);
table.Add(fieldByType, value);
}
}
public T GetValue()
where T : class
{
return Storage.GetValue(this);
}
public void SetValue(T value)
where T : class
{
Storage.SetValue(this, value);
}
}
It can be used like this:
///
/// This class can be used when cloning multiple related objects to store cloned/original object relationship.
///
public class CloningContext
{
readonly FieldByType dictionaries = new FieldByType();
public void RegisterClone(T original, T clone)
{
var dictionary = dictionaries.GetValue>();
if (dictionary == null)
{
dictionary = new Dictionary();
dictionaries.SetValue(dictionary);
}
dictionary[original] = clone;
}
public bool TryGetClone(T original, out T clone)
{
var dictionary = dictionaries.GetValue>();
return dictionary.TryGetValue(original, out clone);
}
}