繁体   English   中英

我如何返回IEnumerable <T> 从一种方法

[英]How do i return IEnumerable<T> from a method

我正在为一个示例项目开发Interface我希望它尽可能通用,所以我创建了一个如下所示的界面

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);
 } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM