我有以下代码:如何判断一个PropertyInfo是否具有特定的枚举类型?
public class DataReader<T> where T : class
{
public T getEntityFromReader(IDataReader reader, IDictionary<string, string> FieldMappings)
{
T entity = Activator.CreateInstance<T>();
Type entityType = entity.GetType();
PropertyInfo[] pi = entityType.GetProperties();
string FieldName;
while (reader.Read())
{
for (int t = 0; t < reader.FieldCount; t++)
{
foreach (PropertyInfo property in pi)
{
FieldMappings.TryGetValue(property.Name, out FieldName);
Type genericType = property.PropertyType;
if (!String.IsNullOrEmpty(FieldName))
property.SetValue(entity, reader[FieldName], null);
}
}
}
return entity;
}
}
当我到Enum
类型的字段,或在这种情况下NameSpace.MyEnum
,我想要做一些特别的东西。我不能简单地SetValue
,因为来自数据库的值是“m”,而Enum
中的值是“Mr”。所以我需要调用另一种方法。我知道!传统系统是否正确?
那么如何确定PropertyInfo
项目何时具有特定的枚举类型?
因此,在上面的代码中,我想先检查PropertyInfo
类型是否是一个特定的枚举类型,如果是,然后调用我的方法,如果不是,则只允许SetValue
运行。
而不是使用Activator.CreateInstance()的使用,只需将“新”约束添加到泛型中:“where T:class,new()”。那么只需使用“T entity = new T()”。这样,您可以在编译时强制使用无参数构造函数。 –
Brannon
2009-10-09 18:11:28
@Brannon,谢谢你的提示。当我进入工作时会做。谢谢。 – griegs 2009-10-10 19:53:52