写了一个类,其中某些属性允许为空,在属性类型上是用int?或者datetime?。
通过类反射给属性赋值时,在进行值的类型转化时出现异常。
代码如下:
//通过类反射,给类的属性赋值//通过类反射,给类的属性赋值
Type t = ql_inf.GetType();
for (i = 0; i < s_rs_sql.FieldCount; i++)
{
     foreach(PropertyInfo pi in t.GetProperties())
     {
         if (pi.Name.ToUpper() == s_rs_sql.GetName(i).ToUpper())
         {
              if(s_rs_sql[i].ToString()!="")
              {
                  pi.SetValue(ql_inf, Convert.ChangeType(s_rs_sql.GetValue(i), pi.PropertyType), null);
                  break;
              }
          }
      }
}请问一下,这个问题怎么解决呢?

解决方案 »

  1.   

    可空类型么?当成Nullable<T>来看就行了。
      

  2.   

    ?是可空泛型结构的简写,实际是System.Nullable<T>...
      

  3.   

    我再补充一些:类里面有这样一个属性:
    private int? days;那么执行这句时:
    pi.SetValue(ql_inf, Convert.ChangeType(s_rs_sql.GetValue(i), pi.PropertyType), null);
    如果s_rs_sql.GetValue(i)为10
    这时候就会出现错误:
    从“System.Int32”到“System.Nullable`1[[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]”的强制转换无效。
      

  4.   

        Type propertyType = pi.PropertyType;
        if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
        {
            propertyType = propertyType.GetGenericArguments()[0];
        }    if (s_rs_sql.GetValue(i) == null)
        {
            pi.SetValue(ql_inf, null, null);
        }
        else
        {
            pi.SetValue(ql_inf, Convert.ChangeType(s_rs_sql.GetValue(i), propertyType), null);
        }
        break;
      

  5.   

    private int? days;
    ------------------如果你想使用反射 为这个名为 days 的字段(域) 赋值的话,可以不用考虑它的类型eg:        Type t = typeof(ClassName);        ClassName classInstance = new ClassName();        foreach (FieldInfo fi in t.GetFields(BindingFlags.NonPublic | BindingFlags.Instance))
            {
                if (fi.Name == "days")
                {                fi.SetValue(classInstance, 10);
                    break;            }
            }
      

  6.   

    public static object ChangeType(this object value, Type conversionType)
            {
                if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
                {
                    if (value != null)
                    {
                        NullableConverter nullableConverter = new NullableConverter(conversionType);
                        conversionType = nullableConverter.UnderlyingType;
                    }                return null;
                }
                return Convert.ChangeType(value, conversionType);
            }