how to set nullable type via reflection code ( c#)?

后端 未结 8 1403
我寻月下人不归
我寻月下人不归 2020-12-28 16:05

I need to set the properties of a class using reflection.

I have a Dictionary with property names and string values.

Inside

8条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-28 16:21

    here is the safest solution for "nullable" object type

    if (reader[rName] != DBNull.Value)
    
        {
            PropertyInfo pi = (PropertyInfo)d[rName.ToLower()];
            if (pi.PropertyType.FullName.ToLower().Contains("nullable"))
                pi.SetValue(item, reader[rName]);
            else
                pi.SetValue(item, Convert.ChangeType(reader[rName], Type.GetType(pi.PropertyType.FullName)), null);
    
        }
    

提交回复
热议问题