无法转换 System.DBNull

Unable to convert System.DBNull

我在从 excel 读取数据时遇到问题。如果单元格为空,我得到异常 "Unable to cast object of type 'System.DBNull' to type 'System.String'" 我研究了 Whosebug,发现可以转换 DBNullValues,我尝试了这个建议,但我的程序甚至在调用转换 DBValues 的方法之前就抛出异常。有什么建议吗?

            int A = reader.GetOrdinal("A");

            foreach (DbDataRecord record in reader)
            {
                string foo = ConvertFromDBVal<string>(record.GetString(A));
            }
        }
        catch
        {

        }
        conn.Close();
        return AllConnections;
    }

    public static T ConvertFromDBVal<T>(object obj)
    {
        if (obj == null || obj == DBNull.Value)
        {
            return default(T);
        }
        else
        {
            return (T)obj;
        }
    }

您正在调用 record.GetString,我预计 that 会失败,因为它正在尝试执行到字符串的转换。您应该能够在堆栈跟踪中看到它。相反,使用 record.GetValue:

string foo = ConvertFromDBVal<string>(record.GetValue(A));

然后它在到达您的方法之前不会执行任何转换。