次のようなコードがあるとします。
while(myDataReader.Read())
{
myObject.intVal = Convert.ToInt32(myDataReader["mycolumn"] ?? 0);
}
エラーがスローされます:
オブジェクトを DBNull から他の型にキャストすることはできません。
nullable int として定義することintVal
はオプションではありません。上記を行う方法はありますか?
次のようなコードがあるとします。
while(myDataReader.Read())
{
myObject.intVal = Convert.ToInt32(myDataReader["mycolumn"] ?? 0);
}
エラーがスローされます:
オブジェクトを DBNull から他の型にキャストすることはできません。
nullable int として定義することintVal
はオプションではありません。上記を行う方法はありますか?
もう1つのオプションがあります:
while (myDataReader.Read())
{
myObject.intVal = (myDataReader["mycolumn"] as int? ?? 0);
}
拡張メソッドを使用できますか?(頭のてっぺんから書き留めた)
public static class DataReaderExtensions
{
public static T Read<T>(this SqlDataReader reader, string column, T defaultValue = default(T))
{
var value = reader[column];
return (T)((DBNull.Value.Equals(value))
? defaultValue
: Convert.ChangeType(value, typeof(T)));
}
}
あなたはそれを次のように使うでしょう:
while(myDataReader.Read())
{
int i = myDataReader.Read<int>("mycolumn", 0);
}
簡単に使えInt32.Tryparse
ますか?
int number;
bool result = Int32.TryParse(myDataReader["mycolumn"].ToString(), out number);
MSDNによるとnumber
、変換が失敗した場合は0が含まれます
次のようなものはどうですか:
object x = DBNull.Value;
int y = (x as Int32?).GetValueOrDefault(); //This will be 0
またはあなたの場合:
int i = (myDataReader["mycolumn"] as Int32?).GetValueOrDefault();
DBNull.Value
null合体演算子( != )以外のものを使用してみませんかnull
:
int i = myDataReader["mycolumn"] == DBNull.Value ?
Convert.ToInt32(myDataReader["mycolumn"]) :
0;
あなたはいつでもそれをきちんとした拡張メソッドでまとめることができます:
public static T Read<T>(this DataReader reader, string column, T defaultVal)
{
if(reader[column] == DBNull.Value) return defaultVal;
return Convert.ChangeType(reader[column], typeof(T));
}
いいえ、ヌルに対してのみ機能します。
DBNull をチェックし、代わりにデフォルト値を返すオブジェクトの拡張メソッドはどうですか?
//may not compile or be syntactically correct! Just the general idea.
public static object DefaultIfDBNull( this object TheObject, object DefaultValue )
{
if( TheObject is DBNull )
return DefaultValue;
return TheObject;
}