ASP.NET偷懒大法六(可空类型的动态赋值)

Nullable是asp.net2.0新增的类型,可以简单的说成是一个泛型结构,对于这种结果前面的章节中动态赋值的方法就不起作用啦。要首先判断他是否是泛型可空型。然后再取出他原始的类型进行赋值

代码如下:

System.Reflection.PropertyInfo propertyInfo = t.GetProperty((var as testTextBox).ID);
if (propertyInfo != null)
{
             bool isNullableValueType = propertyInfo.PropertyType.IsGenericType && (propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>));
            Type genericType = propertyInfo.PropertyType;

             if (isNullableValueType)
                      genericType = propertyInfo.PropertyType.GetGenericArguments()[0];

                       string tempText = (var as testTextBox).Text;
                       if (!string.IsNullOrEmpty(tempText))
                                    propertyInfo.SetValue(entity, Convert.ChangeType(tempText, genericType), null);
}

其中

IsGenericType 判断是否为泛型
GetGenericTypeDefinition() 取得泛型结构的定义

posted @ 2008-06-16 11:05  克隆  阅读(683)  评论(0编辑  收藏  举报