2017-11-21 94 views
5

Bu, bir .NET Core 1.1.4 projesinin içindedir, bu yüzden lütfen bunu dikkate alın.Bir N # Yapılandırılabilir <T> `bir C# işlevine bir Type parametresi olarak geçirme

Bir değerin bir türe atanıp atanmadığını doğrulayan bir işlev oluşturmaya çalışıyorum ancak Nullable<T> türleriyle ilgili bir sorunla karşılaşıyorum.

My fonksiyonu: valuenull ve destinationTypeNullable<T> olduğunu doğrulamak için çalışırsa

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 maddesi Yukarıdaki durumda kolları; else, value aslında bir şey içeriyorsa, madde ele alır, bu nedenle, destinationType atayıp atamayacağınızı veya Nullable<T> ise, bunun T'a atanabileceğini belirlemeyi dener.

Sorun, Nullable<T>'un Type değil, bu nedenle CheckIfAssignable(3, Nullable<Int32>) numaralı çağrı, işlev imzasıyla eşleşmiyor. Bana bir Nullable<T> geçmesi

protected void CheckIsAssignable(Object value, ValueType destinationType) 

sağlar, ama sonra Nullable.GetUnderlyingType bir argüman olarak göndermek olamaz:

için imza değiştirme.

Sorunu bu konu üzerinde aşırı karmaşıklaştırdığımdan emin değilim, ancak görmediğim basit bir çözüm olduğunu hissediyorum.

+5

' null' başka tür gibi bir türüdür: Sen şöyle typeof() komutunu kullanmak gerekir. Diğer türdeki gibi typeof() 'işlevini kullanın. – SLaks

cevap

6

Türün kendisini burada geçirmiyorsunuz.

CheckIfAssignable(3, typeof(Nullable<Int32>)) 
İlgili konular