【问题标题】:How do i return IEnumerable<T> from a method如何从方法返回 IEnumerable<T>
【发布时间】:2023-03-31 06:30:01
【问题描述】:

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

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

【问题讨论】:

    标签: c# class generics collections interface


    【解决方案1】:

    您需要使用通用的interface/class,而不仅仅是generic methods

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

    在接口/类上定义泛型类型可确保该类型在整个类中都是已知的(无论在何处使用类型说明符)。

    【讨论】:

    • btw 和你的回答一样public interface IFactory&lt;Type&gt; { IEnumerable&lt;Type&gt; GetAll(); Type GetOne(int Id); }
    • @Deeptechtons - 差不多。 Type 是一个实际的 .NET 类名,因此这可能会显得模棱两可。但是泛型类型参数的名称可以是任何名称。
    【解决方案2】:

    在接口上声明类型:

    public interface IFactory<T>
    

    【讨论】:

    • +1 虽然你的和 Oded 的一样,但我喜欢他的参考解释方式。
    【解决方案3】:

    编译器无法推断 T 的用途。您还需要在类级别声明它。

    试试:

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

    【讨论】:

      猜你喜欢
      • 2020-09-28
      • 1970-01-01
      • 1970-01-01
      • 2011-01-28
      • 2016-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多