I am trying to learn generics, but there is some things I just cant wrap my head around.
Here are the interfaces and classes in play:
public interface IQueryExecutor
{
T ExecuteQuery<T>(IQuery<T> query);
T ExecuteQuery<T, T1>(IQuery<T, T1> query);
}
public interface IQuery<out T>
{
T Execute();
}
public class StringQuery : IQuery<string>
{
public string Execute()
{
return "String query executed";
}
}
public interface IQuery<out T, in T1>
{
T Execute(T1 input);
}
public class ListQuery : IQuery<List<string>, string>
{
public List<string> Execute(string input)
{
return new List<string>() { input };
}
}
The problem occurs when I try to implement the second method in the queryExecutor:
public class QueryExecutor : IQueryExecutor
{
public T ExecuteQuery<T>(IQuery<T> query)
{
return query.Execute();
}
public T ExecuteQuery<T, T1>(IQuery<T, T1> query)
{
return query.Execute(T1 input);
}
}
I want to pass T1 as parameter to the method implementation, but that is not possible (could be done by using an IoC container like Autofac, but that's not what I want). Help! There must be some very basics of generics I don't understand.
So the question is, how do I implement:
public T ExecuteQuery<T, T1>(IQuery<T, T1> query)
{
return ????
}
You need to pass input parameter somewhere. The best option would be to extend method signature to accept input parameter like this:
public interface IQueryExecutor
{
T ExecuteQuery<T>(IQuery<T> query);
T ExecuteQuery<T, T1>(IQuery<T, T1> query, T1 input);
}
The second option is to remove a second version of your IQuery interface pass input parameter in constructor.
public class ListQuery : IQuery<List<string>>
{
private string _input;
public ListQuery(string input)
{
_input= input;
}
public List<string> Execute()
{
return new List<string>() { _input };
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.