[英]Problem with using a non-abstract type as a generic type in a method
I have this code that I am trying to use in my application: 我有尝试在我的应用程序中使用的以下代码:
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;
}
}
}
However the code is showing this error: 但是代码显示此错误:
Error CS0310: '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 'SQLiteConnection.Query(string, params object[])' 错误CS0310:“ T”必须是具有公共无参数构造函数的非抽象类型,以便在通用类型或方法“ SQLiteConnection.Query(string,params object [])”中将其用作参数“ T”
Can anyone give me advice on what this means and possibly how I can solve the problem. 任何人都可以就这意味着什么以及可能如何解决该问题给我建议。
You must use a Generic Constraint to satisfy the requirement and let the compiler know that the type passed in will always have a parameterless constructor, add where T: new()
to the method definition. 您必须使用通用约束来满足要求,并让编译器知道传入的类型将始终具有无参数构造函数,请在方法定义的where T: new()
添加。 Read more on generic constraints here https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters 在此处阅读有关通用约束的更多信息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.