I have a generic function to create objects from a DataRow
using reflection. I'm using this function to import tables from an Access database:
private static T CreateItemFromRow<T>(DataRow row, IList<PropertyInfo> properties) where T : new()
{
T item = new T();
foreach (var prop in properties)
{
try
{
if (prop.PropertyType.IsEnum)
prop.SetValue(item, row[prop.Name], null); // what to do??
else
prop.SetValue(item, row[prop.Name], null);
}
catch (Exception ex)
{
System.Diagnostics.Debug.Assert(false, string.Format("failed to assign {0} a value of {1}", prop.Name, row[prop.Name]));
}
}
return item;
}
The problem I'm running into is when the property type is an enum
. I've tried using Enum.Parse
, but that hasn't been successful (I can't get anything to compile).
Is there any way to convert the object represented by row[prop.Name]
to the correct enum
using my function? Or do I need to write a special conversion function specific for the enum
s I've defined.
Aucun commentaire:
Enregistrer un commentaire