C# - 处理数据库类型可以是十进制或双精度



我正在使用以下代码将数据从数据库导入到表中:

public double[,] toValueArray(string fieldPrefix, int firstIndex, int lastIndex)
        {
            // return a bunch of value columns as a double array
            double[,] outArr = new double[TableRowCount,lastIndex-firstIndex+1];
            for (int i = firstIndex; i <= lastIndex; i++)
            {
                var col = TheDataTable.Columns[fieldPrefix + i];
                int r = -1;
                foreach (DataRow row in TheDataTable.Rows)
                {                    
                    outArr[++r, i - firstIndex] = (row[col] == null || row[col] == DBNull.Value) ? 0 : (double)row[col];                              
                }
            }
            return outArr; 
        }
问题是,有时

数据库可能会将这些存储为小数,有时是双精度。 如何仅在类型为十进制时才转换使用.toDouble()

首先,使用 0D 具有双精度值和 avoit 将int隐式转换为 double 。转换 您可以尝试使用Convert类型的ToDouble静态方法进行转换。对于示例:

double setValue = 0D;
if (row[col] != null && row[col] != DBNull.Value)))
   setValue = (row[col] is decimal) ? Convert.ToDouble(row[col]) : (double) row[col];
outArr[++r, i - firstIndex] = setValue;

相关内容

最新更新