如何从一个方法返回IEnumerable<T>?

6

我正在为一个示例项目开发界面,我希望它尽可能地通用,因此我创建了以下接口:

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);
}
3个回答

11

您需要使用通用的接口/,而不仅仅是通用方法

public interface IFactory<T>
{    
    IEnumerable<T> GetAll();
    T GetOne(int Id);
}

在接口/类上定义一个通用类型,确保该类型在整个类中得到了知晓(无论类型说明符在何处使用)。


顺便问一下,这个和你的答案一样吗?public interface IFactory { IEnumerable GetAll(); Type GetOne(int Id); } - Deeptechtons
2
@Deeptechtons - 差不多了。Type是一个实际的.NET类名,所以这可能会产生歧义。但是泛型类型参数的名称可以是任何东西。 - Oded

10

在接口上声明类型:

public interface IFactory<T>

虽然你的答案和Oded的一样,但我喜欢他用参考解释的方式,所以给你点赞。 - Deeptechtons

2

编译器无法推断T的含义,您需要在类级别上声明它。

尝试:

 public interface IFactory<T>
 {
     IEnumerable<T> GetAll();
     T GetOne(int Id);
 } 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接