How can I set a value to a "value"-type generic object?
My goal is to retrieve a column of scalar data and convert them into a list of integers.
Suppose, I have the following code snippet:
public class DataAccess
{
SafeDataReader dataReader;
public IList<Tcom> Get<Tcom>(ITransactionManager tm, string SQL, params object[] parameters)
{
T tempO = Activator.CreateInstance<T>();
Object objValue = dataReader.GetFieldValue(0);
...
}
...
}
Its usage can be
public IEnumerable<int> GetIDs()
{
IEnumerable<int> list = null;
TransactionManager tm = new TransactionManager(DBNameConst.CurrentDB);
try
{
tm.BeginTransaction();
list = AgeGroupDataAccess.Get<int>(tm, @"select ID from AgeGroup");
tm.CommitTransaction();
}
catch (Exception)
{
tm.RollbackTransaction();
throw;
}
return list;
}
Here, T
can be either value
types or class
types.
- I know how to set values to a
class
-type.
But, say, T is a value
type like Int32
.
How can I set objValue
to a tempO
?
E.g.
TypeConverter tc = new TypeConverter();
tempO = tc.ConvertTo(objValue, typeof(Tcom));
doesn't work.
Additional source code:
class SafeDataReader
{
private IDataReader reader = null;
//...
public virtual int? GetFieldValue(int columNo)
{
int? data = null;
//int column = reader.GetOrdinal(columnName);
string columnName = reader.GetName(columNo);
if (!reader.IsDBNull(reader.GetOrdinal(columnName)))
{
data = Convert.ToInt32(reader[columnName]);
}
return data;
}
//...
}
Aucun commentaire:
Enregistrer un commentaire