![](/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.