如何返回IEnumerable从一个方法
本文关键字:一个 方法 何返回 返回 IEnumerable | 更新日期: 2023-09-27 18:13:07
我正在为一个示例项目开发接口,我希望它尽可能通用,所以我创建了一个像下面这样的接口
public interface IUserFactory
{
IEnumerable<Users> GetAll();
Users GetOne(int Id);
}
但是后来我不得不复制
下面的界面public interface IProjectFactory
{
IEnumerable<Projects> GetAll(User user);
Project GetOne(int Id);
}
如果你看上面的差异只是他们返回的类型,所以我创建了下面的东西,只发现我得到错误Cannot Resolve Symbol T
我做错了什么
public interface IFactory
{
IEnumerable<T> GetAll();
T GetOne(int Id);
}
您需要使用泛型接口/类,而不仅仅是泛型方法:
public interface IFactory<T>
{
IEnumerable<T> GetAll();
T GetOne(int Id);
}
在接口/类上定义泛型类型确保该类型在整个类中都是已知的(无论在何处使用类型说明符)。
在接口上声明类型:
public interface IFactory<T>
编译器无法推断T的用途。您还需要在类级别声明它。
试题:
public interface IFactory<T>
{
IEnumerable<T> GetAll();
T GetOne(int Id);
}