########从这段代码你能看出点什么问题#############

sunshine_anycall 2009-02-06 02:32:27
    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;
}
}
}
}
...全文
157 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
eynStudio 2009-02-07
  • 打赏
  • 举报
回复
哈哈,太多问题了哦!!!
龙宜坡 2009-02-07
  • 打赏
  • 举报
回复
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;
}
}
}
}


eynStudio 2009-02-06
  • 打赏
  • 举报
回复
学习
龙宜坡 2009-02-06
  • 打赏
  • 举报
回复
静态构造函数具有以下特点:

静态构造函数既没有访问修饰符,也没有参数。

在创建第一个实例或引用任何静态成员之前,将自动调用静态构造函数来初始化类。

无法直接调用静态构造函数。

在程序中,用户无法控制何时执行静态构造函数。

静态构造函数的典型用途是:当类使用日志文件时,将使用这种构造函数向日志文件中写入项。

静态构造函数在为非托管代码创建包装类时也很有用,此时该构造函数可以调用 LoadLibrary 方法。


static MemoryTypeMap()
{
MemoryTypeMap singleton = new MemoryTypeMap();
singleton._dicType.Add(typeof(IWeatherReader), new TypeConstructor(typeof(WeatherReaderImpl), "s"));//这个方法如果是写入文件的话??
}




orain 2009-02-06
  • 打赏
  • 举报
回复
还有你那个静态构造函数里创建的实例 singleton,静态构造函数执行完以后马上就被销毁了,外面根本没法引用啊(连同 singleton._dicType 也会被销毁的)
ztenv 2009-02-06
  • 打赏
  • 举报
回复
private MemoryTypeMap() { }//要么删除这一行才能实例化,要么把public TypeConstructor this[Type type]
写成静态的

static MemoryTypeMap()
{//谁会用到这里声明的singleton呢?没有谁会用到吧?
MemoryTypeMap singleton = new MemoryTypeMap();
singleton._dicType.Add(typeof(IWeatherReader), new TypeConstructor(typeof(WeatherReaderImpl), "s"));
}
orain 2009-02-06
  • 打赏
  • 举报
回复
你定义了一个静态构造函数, 而这个类本身没有静态方法, 同时, 也无法创建类的实例(因为实例构造函数被私有化了(private), 这意味着根本没办法调用到那个静态构造函数, 那么这个类就没有任何用处。
你这样做的目的大约是想构造一个单体模式,但是要注意一点,静态构造函数在一个应用程序域中最多只能执行一次,所以这个语句:
singleton._dicType.Add(typeof(IWeatherReader), new TypeConstructor(typeof(WeatherReaderImpl), "s"));
放入静态构造函数中,其实你只能在字典中增加一个条目而已,所以这句话是没多少实际意义的,你另外还得再实现一个往字典里增加条目的方法才行。
fskang 2009-02-06
  • 打赏
  • 举报
回复
啥意思?写了一个不能初始化的类?

MemoryTypeMap m = (MemoryTypeMap)Activator.CreateInstance(typeof(MemoryTypeMap), true);

caicai_45 2009-02-06
  • 打赏
  • 举报
回复
static 的构造函数, 能实例化 非 static 的字段?

111,131

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧