您好!
我有一个像缓存一样使用的类:
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() 方法中那样为每个缓存明确地执行此操作?
最佳答案
恶心。您必须检查程序集中您感兴趣的所有类型,并检查所有静态字段。这变得更加有趣,因为它是一个通用类型。如果你有一个非泛型基类,你的生活会更简单:
public abstract class MyCache : IDisposable
{
public abstract void Clear();
}
public sealed class MyCache<T> : MyCache
{
// ...
}
然后至少可以相对容易地检测特定字段的类型是否为 MyCache
,获取其值并在其上调用 Clear
,而不用反射通用类型。
虽然这通常是一个令人讨厌的问题 - 您确定要像这样清除所有缓存,而不真正“了解”您正在清除哪些缓存吗?
关于c# - 反射(reflection)的工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/807389/