如何判断 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
运行。
I have the following code:
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;
}
}
When I get to a field of type Enum
, or in this case NameSpace.MyEnum
, I want to do something special. I can't simply SetValue
because the value coming from the database is let's say "m" and the value in the Enum
is "Mr". So I need to call another method. I know! Legacy systems right?
So how do I determine when a PropertyInfo
item is of a particular enumeration type?
So in the above code I'd like to first check whether the PropertyInfo
type is of a specif enum and if it is then call my method and if not then simply allow SetValue
to run.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是我成功使用的
Here is what I use with success
在上面的代码中,
将告诉您当前类型是否是(派生自)枚举。
In your above code,
will get you whether or not the current type is (derived from) an enum or not.
这就是我将数据表转换为强类型列表时的处理方式
This is how I handle when I convert a data table into a strongly typed list