Return list of options

I have the following interface:

public interface Query<TModel>
{
    IList<TModel> GetData();
}

I would like to have some service that can return all query implementations:

public interface IQueryProvider
{
   List<Query<>> GetAllQueries();
}

and then you can call GetData on one:

var queries = provider.GetAllQueries();
var results = queries[0].GetData();

Can this be achieved with generics?

+3
source share
3 answers

You cannot use an open generic type Query<>, except typeof(). If you want to refer to a set of queries (no type is specified), you will need a non-generic API, for example:

public interface IQuery {
     IList GetData();
     Type QueryType { get; }
}
public interface IQuery<TModel> : IQuery
{
    new IList<TModel> GetData();
}    
public interface IQueryProvider
{
   List<IQuery> GetAllQueries();
}

, , , IQuery , . , , - IQuery<Foo>, IQuery<Bar> - , QueryType.

+4

IQueryProvider , IQuery . , .

1. IQueryProvider

public interface IQueryProvider<TModel>
{
    List<IQuery<TModel>> GetAllQueries();
}

2:

public interface IQueryProvider
{
    List<IQuery<TModel>> GetAllQueries<TModel>();
}

, Query IQuery .

0

IList<> IEnumerable<>, . , ReadOnlyList<> ReadOnlyCollection<> ( , MS).

public interface Query<out TModel>
{
    IEnumerable<TModel> GetData();
}

public interface IQueryProvider
{
   List<Query<object>> GetAllQueries();
}

, TModel s.

0

All Articles