我有一個函數來反序列化我從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);
}
@Cody Gray您沒有看到?他已經使用類型約束!問題是不同的 – Adrian
@adjan OP只在一個地方使用類型約束。有錯誤的行在沒有類型約束的方法中。所以它仍然是重複的。 – Stijn
@Stijn但另一個問題在哪裏說這是每個方法都要求的要求? – Adrian