调用函数 'GetUnderlyingType' 的引用 'GetUnderlyingType' return 可能为空

Reference 'GetUnderlyingType' return from call to function 'GetUnderlyingType' may be null

我在进行代码分析时遇到了 Klocwork 问题,

调用函数 'GetUnderlyingType' 的引用 'GetUnderlyingType' return 可能为 null

if (Nullable.GetUnderlyingType(objProperty.PropertyType) != null)
                {
                    value = row[columnname].ToString().Replace("$", "").Replace(",", "");
                    objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(Nullable.GetUnderlyingType(objProperty.PropertyType).ToString())), null);
                }
                else
                {
                    value = row[columnname].ToString().Replace("%", "");
                    objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(objProperty.PropertyType.ToString())), null);
                }

From the documentation

Return Value
Type: System.Type

The type argument of the nullableType parameter, if the nullableType parameter is a closed generic nullable type; otherwise, null

您使用外部 if 子句处理此问题,但 VisualStudio 似乎无法识别它。解决方案是这样的:

var ut = Nullable.GetUnderlyingType(objProperty.PropertyType);
if (ut != null)
{
    value = row[columnname].ToString().Replace("$", "").Replace(",", "");
    objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(ut.ToString())), null);
}
else
{
    value = row[columnname].ToString().Replace("%", "");
    objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(objProperty.PropertyType.ToString())), null);
}