gri*_*egs 10 c# enums 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;
}
}
Run Code Online (Sandbox Code Playgroud)
当我到达一个类型的领域Enum,或者在这种情况下NameSpace.MyEnum,我想做一些特别的事情.我不能简单地SetValue因为来自数据库的值是"m"而值Enum是"Mr".所以我需要调用另一种方法.我知道!遗产系统对吗?
那么如何确定PropertyInfo项目何时属于特定的枚举类型?
所以在上面的代码中,我想首先检查PropertyInfo类型是否是一个特定的枚举,如果是,那么调用我的方法,如果没有,那么只需允许SetValue运行.
Val*_*mas 28
以下是我成功使用的内容
property.PropertyType.IsEnum
Run Code Online (Sandbox Code Playgroud)
static void DoWork()
{
var myclass = typeof(MyClass);
var pi = myclass.GetProperty("Enum");
var type = pi.PropertyType;
/* as itowlson points out you could just do ...
var isMyEnum = type == typeof(MyEnum)
... becasue Enums can not be inherited
*/
var isMyEnum = type.IsAssignableFrom(typeof(MyEnum)); // true
}
public enum MyEnum { A, B, C, D }
public class MyClass
{
public MyEnum Enum { get; set; }
}
Run Code Online (Sandbox Code Playgroud)