欢迎光临!
我有一个像缓存一样使用的类:
public sealed class MyCache<T> : IDisposable
{
private ReaderWriterLockSlim theLock = new ReaderWriterLockSlim();
private Dictionary<int, T> theCache = new Dictionary<int, T>();
public void Add(int key, T value)
{
// ... logic/code to add to the dictionary
}
public void Clear()
{
theLock.EnterWriteLock();
try
{
theCache.Clear();
}
finally
{
theLock.ExitWriteLock();
}
}
}该缓存被多次使用,因此在任何给定时间通常都有多个该缓存的实例。
示例1:
public static class SpecialPageCache
{
public static MyCache<string> SpecialPage = new MyCache<string>();
}示例2:
public static class DdListCache
{
public static MyCache<List<int, string>> DdlList = new MyCache<List<int, string>>();
}诸若此类。
我有一个可以按需清除缓存的服务,但不幸的是,每个缓存都必须像这样清除:
private void ClearThemAll()
{
SpecialPageCache.SpecialPage.Clear();
DdListCache.DdlList.Clear();
// repeat for all other caches that may exist ...
}我如何使用反射(或其他东西?)调用每个缓存的Clear()方法,而不必像上面的ClearThemAll()方法那样显式地为每个缓存调用它?
发布于 2009-04-30 15:14:18
尼克。您必须遍历程序集中您感兴趣的所有类型,并检查所有静态字段。这使它变得更加有趣,因为它是泛型类型。如果你有一个非通用的基类,你的生活将会更简单:
public abstract class MyCache : IDisposable
{
public abstract void Clear();
}
public sealed class MyCache<T> : MyCache
{
// ...
}然后,至少可以相对容易地检测特定字段的类型是否为MyCache,获取它的值并在其上调用Clear,而不需要在泛型类型上进行反射。
然而,这通常是一个令人讨厌的问题--你确定要像这样清除所有的缓存,而不是真正“了解”你正在清除哪些缓存吗?
发布于 2009-04-30 15:27:02
public interface ICache : IDisposable
{
void Clear();
}
public interface ICache<T> : ICache
{
}
public abstract class CacheBase<T> : ICache<T>
{
}
public sealed class SpecialPageCache : CacheBase<string>
{
internal SpecialPageCache()
{
}
}
public static class CacheFactory
{
private static List<ICache> cacheList = new List<ICache>();
public static TCache Create<TCache>()
where TCache : ICache, new()
{
var result = new TCache();
cacheList.Add(result);
return result;
}
public static void ClearAll()
{
cacheList.ForEach((c) => c.Clear());
}
}发布于 2009-04-30 15:10:26
您可以将对所有实例化缓存的引用存储在列表中。然后迭代相同的列表,并在每个MyCache上调用Clear。=)
https://stackoverflow.com/questions/807389
复制相似问题