2017-11-21 53 views
5

これは.NET Core 1.1.4プロジェクト内にありますので、これを考慮してください。`Nullable <T> 'をTypeパラメータとしてC#関数に渡す

値を型に割り当てることができるかどうかを確認する関数を作成しようとしていますが、Nullable<T>型の問題が発生しています。

My機能:

protected void CheckIsAssignable(Object value, Type destinationType) 
    { 
     if (value == null) 
     { 
      // Nullable.GetUnderlyingType returns null for non-nullable types. 
      if (Nullable.GetUnderlyingType(destinationType) == null) 
      { 
       var message = 
        String.Format(
         "Property Type mismatch. Tried to assign null to type {0}", 
         destinationType.FullName 
        ); 
       throw new TargetException(message); 
      } 
     } 
     else 
     { 
      // If destinationType is nullable, we want to determine if 
      // the underlying type can store the value. 
      if (Nullable.GetUnderlyingType(destinationType) != null) 
      { 
       // Remove the Nullable<T> wrapper 
       destinationType = Nullable.GetUnderlyingType(destinationType); 
      } 
      // We can now verify assignability with a non-null value. 
      if (!destinationType.GetTypeInfo().IsAssignableFrom(value.GetType())) 
      { 
       var message = 
        String.Format(
         "Tried to assign {0} of type {1} to type {2}", 
         value, 
         value.GetType().FullName, 
         destinationType.FullName 
        ); 
       throw new TargetException(message); 
      } 
     } 
    } 

上記if句はvaluenullある場合場合を処理し、destinationTypeNullable<T>であることを確認しようと試みます。 else句は実際に何かが含まれている場合に処理します。したがって、destinationTypeに割り当てることができるかどうかを判断します。Nullable<T>の場合はTに割り当てられます。

問題は、Nullable<T>Typeではないため、CheckIfAssignable(3, Nullable<Int32>)を呼び出すことが関数のシグネチャと一致しないことです。

に署名を変更する:

protected void CheckIsAssignable(Object value, ValueType destinationType) 

すると私はNullable<T>を渡すことができますが、その後、私はNullable.GetUnderlyingTypeの引数としてそれを提出することはできません。

これで問題が複雑化しているかどうかはわかりませんが、私には見えない簡単な解決策があると感じています。

+5

'NULL可能は'他のタイプと同様に、タイプです。 'typeof()'は、他の型と同様に使用します。 – SLaks

答えて

6

あなたはタイプ自体を渡していません。あなたはそのようtypeof()コマンドを使用する必要があります。

CheckIfAssignable(3, typeof(Nullable<Int32>)) 
関連する問題