简体   繁体   中英

Typecast any OleDbReader Double/Int16/Int32/Int64 to C# double?

If I create a new OleDbReader as follows:

OleDbCommand command = new OleDbCommand(query, ActiveConnection);
reader = command.ExecuteReader();
while(reader.Read())
{
   someList.Add((double)reader["columnHeader"]);
}

How can I ensure that I'm always returned a double from the column specified, if the data returned is typed as Int16/Int32/Int64 instead of Double? Do I have to create a handler for each possible type? I know Double.Parse exists but it only accepts strings. So, while I could use ToString() beforehand I feel that this is probably not the most straightforward way to typecast.

Similarly, for another column, I wish to ensure that any String/Double/Int16/Int32/Int64 values return as strings. Will ToString() handle these cases?

I'm fine with potential overflow errors, as I'll check for exceptions regardless.

You should call Convert.ToDouble() , which has a handler for each type.

By contrast, ToString() will work for any non-null value. (as long as it overrides ToString() ; all numeric types do)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM