接口与泛型函数
本文关键字:函数 泛型 接口 | 更新日期: 2023-09-27 18:17:54
我有一个这样的界面:
public interface ITableData
{
List<T> ListAll<T>() where T : TableData;
void Insert(Object o);
}
和我的类实现接口:
public class BookData:ITableData
{
public List<T> ListAll<T>() where T : TableData
{
//some code here
}
}
实际上,我希望得到这样的结果:
public class BookData:ITableData
{
public List<Book> ListAll()
{ List<Book> bookList =XXXXXX;
//some code here
return bookList}
}
如何实现?谢谢所有。
将泛型参数移动到接口而不是方法上:
public interface ITableData<T> where T : TableData
{
List<T> ListAll();
void Insert(Object o);
}
public class BookData : ITableData<Book>
{
public List<Book> ListAll()
{
List<Book> bookList =XXXXXX;
//some code here
return bookList;
}
}
出现问题是因为
public List<Book>
不是接口方法
的有效实现List<T> ListAll<T>() where T : TableData
这样做的原因是您的接口显式地声明T
可以是任何TableData
。因为你的方法只适用于Book
对象,而不是任何TableData
对象,你会得到一个错误。
解决方案是实现一个通用接口:
public interface ITableData<T> where T : TableData
// Implement your methods using T
,你可以在你的类中这样实现:
public class BookData:ITableData<Book>