How do i return IEnumerable from a method

2019-06-19 01:35发布

问题:

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

回答1:

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).



回答2:

Declare the type on the interface:

public interface IFactory<T>


回答3:

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