2016-08-26 67 views
20

我在.net 4.6.2此代碼,現在正試圖轉換成淨核心不過我收到錯誤.Net核心中缺少IsGenericType&IsValueType?

錯誤CS1061「類型」不包含「IsGenericType」 並沒有擴展名的定義方法「IsGenericType」接受 類型「類型」的第一個參數可以找到(是否缺少using指令或一個 集引用?)

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 Systemusing 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