2017-06-16 52 views
0

我有一個函數來反序列化我從Api獲得的任何類型的對象。 如果有錯誤,我想返回類型T的新對象通用T - 創建新實例

我試着用return new T()做到這一點,但我得到的錯誤:

'T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method

這有什麼錯我的代碼?

[SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")] 
     internal static T DeserializeObject<T>(this JsonSerializer serializer, string value) 
     { 
      try 
      { 
       using (var stringReader = new StringReader(value)) 
       { 
        using (var jsonTextReader = new JsonTextReader(stringReader)) 
        { 
         return (T)serializer.Deserialize(jsonTextReader, typeof(T)); 
        } 
       } 
      } 

      catch { 

       return GetDefault<T>(); //This line returns the error 
      } 
     } 


     public static T GetDefault<T>() where T : new() 
     { 
      if (typeof(IEnumerable).IsAssignableFrom(typeof(T))) 
      { 
       return new T(); 
      } 
      return default(T); 
     } 
+0

@Cody Gray您沒有看到?他已經使用類型約束!問題是不同的 – Adrian

+0

@adjan OP只在一個地方使用類型約束。有錯誤的行在沒有類型約束的方法中。所以它仍然是重複的。 – Stijn

+0

@Stijn但另一個問題在哪裏說這是每個方法都要求的要求? – Adrian

回答

3

DeserializeObject<T>您呼叫

GetDefault<T>() 

它具有類型參數約束where T : new(),但DeserializeObject<T>T是不受約束的。您還必須將約束添加到DeserializeObject<T>以及:

internal static T DeserializeObject<T>(this JsonSerializer serializer, string value) : where T : new() 
+0

非常感謝,它的工作 –

+0

@adjan我承認我回答與Visual Studio關閉。 =)剛剛刪除了評論。 –

+0

@Rahul我明白了,現在我明白了。剛剛刪除了評論。 –