Cas*_*rah 6 c# static-constructor
我有一些类来缓存数据库中的数据,这些类在调用静态构造函数时会加载数据.
我需要在所有这些类中调用静态Reload方法,除了那些尚未初始化的类.
例如:City缓存数据库中的数据
public class City
{
public City Get(string key)
{
City city;
FCities.TryGetValue(key, out city);
return city;
}
private static Dictionary<string, City> FCities;
static City()
{
LoadAllCitiesFromDatabase();
}
public static void Reload()
{
LoadAllCitiesFromDatabase();
}
private static void LoadAllCitiesFromDatabase()
{
// Reading all citynames from database (a very slow operation)
Dictionary<string, City> loadedCities = new Dictionary<string, City>();
...
FCities = loadedCities;
}
}
Run Code Online (Sandbox Code Playgroud)
问题是City可能尚未使用(它可能不会在此服务中使用),因此没有理由从数据库加载它.
我重新加载所有方法看起来很像这样:
public static class ReloadAll
{
public static void Do()
{
foreach (Type classType in AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes()).Where(t => t.IsClass && !t.IsAbstract))
{
MethodInfo staticReload = classType.GetMethods().FirstOrDefault(m => m.IsStatic && m.IsPublic && m.ReturnType == typeof(void) && m.Name == "Reload" && m.GetParameters().Length == 0);
if (staticReload != null)
{
if (StaticConstructorHasBeenCalled(classType))
staticReload.Invoke(null, null);
}
}
}
private bool StaticConstructorHasBeenCalled(Type classType)
{
// How do I check if static constructor has been called?
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
我需要一点帮助来实现StaticConstructorHasBeenCalled.
乍一看,我认为这可能是<grin>
量子力学哥本哈根解释可能适用的问题(" 一旦你看它,它就会改变 ").</grin>
即你在课堂上做的任何事情,以观察它是否已被初始化可能会导致它自己初始化...
但是您不必在类中执行此操作,只需在其他位置(除了这些静态类之外)保留一个列表,该列表在初始化时由每个静态类填充.然后在你的重置函数中,只需遍历列表中的类.