为什么这个可空类型会抛出异常

时间:2011-12-21 17:05:28

标签: c# nullable

说我有以下字典:

 public static Dictionary<Type, string> nullableTypeToStringMap = new Dictionary<Type, string>()
    {
        {typeof(bool?)    ,  "bool?"},   
        {typeof(byte?)    ,  "byte?"},   
        {typeof(sbyte?)   ,  "sbyte?"},  
        {typeof(char?)    ,  "char?"},    
        {typeof(decimal?) ,  "decimal?"},
        {typeof(double?)  ,  "double?"}, 
        {typeof(float?)   ,  "float?"},  
        {typeof(int?)     ,  "int?"},     
        {typeof(uint?)    ,  "uint?"},   
        {typeof(long?)    ,  "long?"},   
        {typeof(ulong?)   ,  "ulong?"},  
        {typeof(short?)   ,  "short?"},  
        {typeof(ushort?)  ,   "ushort?"}
    };

并说我执行了这一行:

nullableTypeToStringMap [typeof(int?)];

我收到以下异常:The type initializer for 'DatabaseUtils.Utils.TypeMap' threw an exception.

但是,如果我执行此行:

nullableTypeToStringMap [typeof(int)];

工作正常。知道可以为空的类型导致我出现问题的原因吗?

1 个答案:

答案 0 :(得分:3)

我的通灵调试技巧告诉我你的代码在早期的静态字段初始化程序中,所以它在你指定nullableTypeToStringMap之前就已经运行了。
您需要对静态字段进行排序,以便在初始化之前不使用字段。

相关问题