I have a method in which one of the parameters is an object of an abstract class - ObjectMapper - whose purpose is to convert an object from one class to another from another class. Below, the method signature informs that the objectMapper will receive as input a DbDataReader and will return a generic object T
public T Select<T>(string query, ObjectMapper<T, DbDataReader> objectMapper)
{
var reader = dbConnector.CreateCommand(query).ExecuteReader();
try
{
return objectMapper.from(reader);
}
catch (Exception e)
{
throw e;
}
finally
{
reader.Close();
}
}
As I come from the Java background, for cases that do not need to create a class, just use an anonymous class. However, it seems that C # does not provide this functionality, so I could invoke the method as below
Select<Pessoa>("SELECT * FROM PESSOA", new ObjectMapper<Pessoa, DbDataReader>() {
public override Pessoa from(DbDataReader reader) {
Pessoa p = new Pessoa();
/** Populo o objeto p a partir do objeto DbDataReader **/
return p;
}
});
What should you do to adapt - or even create a new method - so that I can pass an "anonymous class" to the Select method?
UPDATE
The ObjectMapper class
public abstract class ObjectMapper<T, Source>
{
public abstract T from(Source source);
public static bool hasColumnName(DbDataReader reader, string columnName)
{
for (int i = 0; i < reader.FieldCount; i++)
{
if (reader.GetName(i).Equals(columnName, StringComparison.InvariantCultureIgnoreCase))
{
return true;
}
}
return false;
}
/** Outros métodos utilitários **/
}
This class would be an adaptation of the RowMapper class, used by the Spring framework