![](/img/trans.png)
[英]T must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'TModel' in the generic type or method
[英]Problem with using a non-abstract type as a generic type in a method
我有嘗試在我的應用程序中使用的以下代碼:
public partial class DataManager
{
public DataManager()
{
db2 = DependencyService.Get<ISQLiteDB2>().GetConnection();
}
T RunQuery<T>(string qry)
{
lock (l)
{
try
{
T data = db2.Query<T>(qry);
return data;
}
catch (Exception ex)
{
Debug.WriteLine(ex);
Console.WriteLine(qry);
throw;
}
}
}
但是代碼顯示此錯誤:
錯誤CS0310:“ T”必須是具有公共無參數構造函數的非抽象類型,以便在通用類型或方法“ SQLiteConnection.Query(string,params object [])”中將其用作參數“ T”
任何人都可以就這意味着什么以及可能如何解決該問題給我建議。
您必須使用通用約束來滿足要求,並讓編譯器知道傳入的類型將始終具有無參數構造函數,請在方法定義的where T: new()
添加。 在此處閱讀有關通用約束的更多信息https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters
public partial class DataManager
{
public DataManager()
{
db2 = DependencyService.Get<ISQLiteDB2>().GetConnection();
}
List<T> RunQuery<T>(string qry) where T: new()
{
lock (l)
{
try
{
List<T> data = db2.Query<T>(qry);
return data;
}
catch (Exception ex)
{
Debug.WriteLine(ex);
Console.WriteLine(qry);
throw;
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.