2016-08-26 5 views
20

У меня есть этот код в .Net 4.6.2 и теперь пытается преобразовать в .Net ядра, однако я получаю ошибкиIsGenericType & IsValueType отсутствует в .Net Core?

Ошибка CS1061 «Type» не содержит определение для «IsGenericType» и без расширения метод «IsGenericType» принимать первый аргумент типа «типа» может быть найдено (вы пропали без вести с помощью директивы или ссылка сборку?)

public static class StringExtensions 
{ 
    public static TDest ConvertStringTo<TDest>(this string src) 
    { 
     if (src == null) 
     { 
      return default(TDest); 
     }   

     return ChangeType<TDest>(src); 
    } 

    private static T ChangeType<T>(string value) 
    { 
     var t = typeof(T); 

     // getting error here at t.IsGenericType 
     if (t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) 
     { 
      if (value == null) 
      { 
       return default(T); 
      } 

      t = Nullable.GetUnderlyingType(t); 
     } 

     return (T)Convert.ChangeType(value, t); 
    } 
} 

Что такое эквивалент в .Net Ядра?

Update1

Удивительно, когда я отладки кода я вижу, переменная t имеет свойство IsGenericType однако я не могу использовать IsGenericType в коде. Не знаете, почему или какое пространство имен мне нужно добавить. Я добавил using System и using System.Runtime как пространство имен

enter image description here

ответ

30

Да, они перемещаются в .Net Ядра к новому TypeInfo класса. Способ получения этой работы - использовать GetTypeInfo().IsGenericType & GetTypeInfo().IsValueType.

using System.Reflection; 

public static class StringExtensions 
{ 
    public static TDest ConvertStringTo<TDest>(this string src) 
    { 
     if (src == null) 
     { 
      return default(TDest); 
     }   

     return ChangeType<TDest>(src); 
    } 

    private static T ChangeType<T>(string value) 
    { 
     var t = typeof(T); 

     // changed t.IsGenericType to t.GetTypeInfo().IsGenericType 
     if (t.GetTypeInfo().IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) 
     { 
      if (value == null) 
      { 
       return default(T); 
      } 

      t = Nullable.GetUnderlyingType(t); 
     } 

     return (T)Convert.ChangeType(value, t); 
    } 
} 
+2

@svick Метод 'GetTypeInfo()' в другом пространстве имен? intelisense не может найти его – LP13

+4

Не знаете, почему вы спрашиваете меня, но да, это в 'System.Reflection'. – svick

 Смежные вопросы

  • Нет связанных вопросов^_^