Class CacheDictionary<TKey, T>
Represents a dictionary that caches items and provides methods to manage the cache.
Inheritance
Namespace: UniUtils.Data
Assembly: cs.temp.dll.dll
Syntax
public abstract class CacheDictionary<TKey, T> : EphemeralSingleton<CacheDictionary<TKey, T>>
Type Parameters
Name | Description |
---|---|
TKey | The type of the key used in the dictionary. |
T | The type of the value stored in the dictionary. |
Examples
Example of using a cache to store surface types based on a ground transform:
public class SurfaceType
{
public string type;
}
public class GroundSurfaceCache : CacheDictionary<Transform, string> { }
public class Player
{
public void OnFootstep(Transform groundTransform)
{
string surfaceType = GroundSurfaceCache.Instance.GetOrAdd(
groundTransform,
transform => transform.GetComponent<SurfaceType>()?.type,
discardNullValue: true
);
Debug.Log("Footstep on surface: " + surfaceType);
}
}
Methods
AddCachedItem(TKey, T)
Adds or updates an item in the cache.
Declaration
public void AddCachedItem(TKey key, T value)
Parameters
Type | Name | Description |
---|---|---|
TKey | key | The key of the item to add or update. |
T | value | The value to associate with the key. |
ClearCache()
Clears all items from the cache.
Declaration
public void ClearCache()
ContainsKey(TKey)
Determines whether the cache contains the specified key.
Declaration
public bool ContainsKey(TKey key)
Parameters
Type | Name | Description |
---|---|---|
TKey | key | The key to check for existence. |
Returns
Type | Description |
---|---|
System.Boolean |
|
GetOrAdd(TKey, Func<TKey, T>, Boolean)
Retrieves a value from the cache or adds it using the specified factory function if it does not exist.
Declaration
public T GetOrAdd(TKey key, Func<TKey, T> valueFactory, bool discardNullValue = true)
Parameters
Type | Name | Description |
---|---|---|
TKey | key | The key to retrieve or add. |
Func<TKey, T> | valueFactory | The function used to create the value if it does not exist. |
System.Boolean | discardNullValue | Indicates whether to discard null values. Defaults to |
Returns
Type | Description |
---|---|
T | The value associated with the key. |
RemoveCachedItem(TKey)
Removes an item from the cache.
Declaration
public void RemoveCachedItem(TKey key)
Parameters
Type | Name | Description |
---|---|---|
TKey | key | The key of the item to remove. |
TryGetValue(TKey, out T)
Attempts to retrieve a value from the cache.
Declaration
public bool TryGetValue(TKey key, out T value)
Parameters
Type | Name | Description |
---|---|---|
TKey | key | The key to retrieve. |
T | value | When this method returns, contains the value associated with the key if found; otherwise, the default value for the type of the value parameter. |
Returns
Type | Description |
---|---|
System.Boolean |
|