public class MemoryTypeMap
{
private Dictionary<Type, TypeConstructor> _dicType = new Dictionary<Type, TypeConstructor>();
private ITypeMap _typeMapInstance; private MemoryTypeMap() { } static MemoryTypeMap()
{
MemoryTypeMap singleton = new MemoryTypeMap();
singleton._dicType.Add(typeof(IWeatherReader), new TypeConstructor(typeof(WeatherReaderImpl), "s"));
} public TypeConstructor this[Type type]
{
get
{
TypeConstructor constructor; if(!_dicType.TryGetValue(type,out constructor))
{
return null;
}
else
{
return constructor;
}
}
}
}
{
private Dictionary<Type, TypeConstructor> _dicType = new Dictionary<Type, TypeConstructor>();
private ITypeMap _typeMapInstance; private MemoryTypeMap() { } static MemoryTypeMap()
{
MemoryTypeMap singleton = new MemoryTypeMap();
singleton._dicType.Add(typeof(IWeatherReader), new TypeConstructor(typeof(WeatherReaderImpl), "s"));
} public TypeConstructor this[Type type]
{
get
{
TypeConstructor constructor; if(!_dicType.TryGetValue(type,out constructor))
{
return null;
}
else
{
return constructor;
}
}
}
}
你这样做的目的大约是想构造一个单体模式,但是要注意一点,静态构造函数在一个应用程序域中最多只能执行一次,所以这个语句:
singleton._dicType.Add(typeof(IWeatherReader), new TypeConstructor(typeof(WeatherReaderImpl), "s"));
放入静态构造函数中,其实你只能在字典中增加一个条目而已,所以这句话是没多少实际意义的,你另外还得再实现一个往字典里增加条目的方法才行。
写成静态的 static MemoryTypeMap()
{//谁会用到这里声明的singleton呢?没有谁会用到吧?
MemoryTypeMap singleton = new MemoryTypeMap();
singleton._dicType.Add(typeof(IWeatherReader), new TypeConstructor(typeof(WeatherReaderImpl), "s"));
}
static MemoryTypeMap()
{
MemoryTypeMap singleton = new MemoryTypeMap();
singleton._dicType.Add(typeof(IWeatherReader), new TypeConstructor(typeof(WeatherReaderImpl), "s"));//这个方法如果是写入文件的话??
}
{
private Dictionary<Type, TypeConstructor> _dicType = new Dictionary<Type, TypeConstructor>();
private ITypeMap _typeMapInstance; private MemoryTypeMap() { } static MemoryTypeMap()
{
MemoryTypeMap singleton = new MemoryTypeMap(); //这样是否会导致无限递归?????、????
singleton._dicType.Add(typeof(IWeatherReader), new TypeConstructor(typeof(WeatherReaderImpl), "s"));
} public TypeConstructor this[Type type]
{
get
{
TypeConstructor constructor; if(!_dicType.TryGetValue(type,out constructor))
{
return null;
}
else
{
return constructor;
}
}
}
}