我有以下代碼:如何判斷一個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