2016-09-22 1 views
1

をキャスト私はそうのように見える小さなユーティリティメソッドがあります:私は、データテーブルのうち、記録を取って、特定のフィールドを取っています、私の特定のシナリオでボックス化解除と一般的な方法で1つのステートメントで

/// <summary> 
/// Replaces a DBNull value with the default of the type specified 
/// </summary> 
/// <typeparam name="T">Resulting type</typeparam> 
/// <param name="p_this">Object to check for DBNull</param> 
/// <returns>p_this if it is not DBNull.Value, else default(T)</returns> 
public static T ReplaceDBNullWithDefault<T>(this object p_this) 
{ 
    return p_this == System.DBNull.Value ? default(T) : (T)p_this; 
} 

をそれから弱いタイプを使用して、私が得ている特定のフィールドはobjectに囲まれているlongです。

var obj = 2934L; 
int num = obj.ReplaceDBNullWithDefault<int>(); 

それは、(T)p_thisで、InvalidCastExceptionで失敗し、次のようにこれを再現する例があります。

object myLong = 234L; 
int myInt = (int)myLong; 

しかし、アンボクシングして、キャスト正常に動作します:

私はlongintに直接キャストし、このようにそれをやろうとするも失敗することはできません箱入りの理由を、理解

object myLong = 234L; 
int myInt = (int)(long)myLong; 

私の方法でこれを回避するにはどうしたらいいですか?

+0

はあなたがint' 'にキャストされている理由ではなく、long''に手の込んだてもらえますか? (したがって、 'long'として' T'を指定します) –

+0

正しい型を指定することによって) –

+0

結果を入れているフィールドは 'long'ではなく' int'です。私はちょうどそこにキャストをすることができたと思う。 – Logan

答えて

0

あなたはこれを試すことができます:あなたは、コンバーチブルないタイプには、この機能を適用しようとしたとき

public static T ReplaceDBNullWithDefault<T>(this object p_this) where T : struct 
{ 
    return 
     p_this == System.DBNull.Value 
      ? default(T) 
      : (T)Convert.ChangeType(p_this, typeof(T)); 
} 

それにもかかわらず、あなたが例外を取得します。

おそらく、既知のタイプに値を手動でキャストする方が良いでしょう。

0

あなたは、このアプローチを使用することができます。

/// <summary> 
/// Replaces a DBNull value with the default of the type specified 
/// </summary> 
/// <typeparam name="T">Resulting type</typeparam> 
/// <param name="value">Object to check for DBNull</param> 
/// <param name="tryConvert">if true the object will be converted to the target type if possible, otherwise an InvalidCastException is raised</param> 
/// <returns>p_this if it is not DBNull.Value, else default(T)</returns> 
/// <exception cref="InvalidCastException">Thrown if the target type is incorrect and the value could not be converted to it</exception> 
public static T ReplaceDbNullWithDefault<T>(this object value, bool tryConvert = true) 
{ 
    if (value == System.DBNull.Value || value == null) 
     return default(T); 
    if (value is T) 
     return (T) value; 
    if(!tryConvert || !(value is IConvertible)) 
     throw new InvalidCastException($"Cannot convert {value.GetType()} to {typeof(T)}."); 
    return (T)((IConvertible) value).ToType(typeof(T), null); 
} 
関連する問題