How do i return IEnumerable from a method

2019-06-19 02:10发布

I am developing Interface for a sample project i wanted it to be as generic as possible so i created a interface like below

public interface IUserFactory
{    
    IEnumerable<Users> GetAll();
    Users GetOne(int Id);
}

but then it happened i had to duplicate the interface to do below

public interface IProjectFactory
{    
    IEnumerable<Projects> GetAll(User user);
    Project GetOne(int Id);
}

if you looked at above difference is just types they return, so i created something like below only to find i get error Cannot Resolve Symbol T What am i doing wrong

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

3条回答
贼婆χ
2楼-- · 2019-06-19 02:15

The compiler cannot infer what the T is for. You need to declare it at the class level as well.

Try:

 public interface IFactory<T>
 {
     IEnumerable<T> GetAll();
     T GetOne(int Id);
 } 
查看更多
Lonely孤独者°
3楼-- · 2019-06-19 02:18

You need to use a generic interface/class, not just generic methods:

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

Defining a generic type on the interface/class ensures the type is known throughout the class (wherever the type specifier is used).

查看更多
欢心
4楼-- · 2019-06-19 02:25

Declare the type on the interface:

public interface IFactory<T>
查看更多
登录 后发表回答