无法将 DBNull.Value 转换为类型“System.Double”。请使用可为 null 的类型

Chr*_*ris 4 .net c# reflection

我的object val = method.Invoke line中的代码有问题。我们使用此代码将 mdx 字段映射到我们的实体(集合)。某些数据具有 DBNull 值。所以我做了一项研究来检查 propertyType 是否为 Nullable 并实现了解决方案。请参阅Nullable.GetUnderlyingType。但我仍然遇到这个错误。无法将 DBNull.Value 转换为类型“System.Double”。请使用可为空的类型。

string propertyKey = entry.Key;
PropertyInfo property = entry.Value;
Type propertyType = property.PropertyType;

propertyType = Nullable.GetUnderlyingType(propertyType) ?? propertyType;

object objectNeedingProperty = objectToPopulate;

MethodInfo method = _dataRowExtFieldMethod.MakeGenericMethod(new Type[] { propertyType });
object val = method.Invoke(row, new object[] { row, propertyKey });

property.SetValue(objectNeedingProperty, val, null);
Run Code Online (Sandbox Code Playgroud)

tra*_*max 5

您的对象具有 type 属性double。将其更改为double?以便您可以为该属性分配空值。