2009-10-08 85 views
9

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

+1

而不是使用Activator.CreateInstance ()的使用,只需將「新」約束添加到泛型中:「where T:class,new()」。那麼只需使用「T entity = new T()」。這樣,您可以在編譯時強制使用無參數構造函數。 – Brannon 2009-10-09 18:11:28

+0

@Brannon,謝謝你的提示。當我進入工作時會做。謝謝。 – griegs 2009-10-10 19:53:52

回答

2
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; } 
} 
+2

測試type == typeof(MyEnum)可能會更清晰。 IsAssignableTo不會添加任何值,因爲您不能從MyEnum派生另一個類型。 – itowlson 2009-10-08 23:18:25

+0

謝謝@Matthew。像買一個一樣工作。 – griegs 2009-10-08 23:27:06

3

在你上面的代碼,

bool isEnum = typeof(Enum).IsAssignableFrom(typeof(genericType)); 

會讓你是否當前的類型(源於)枚舉與否。

+0

+1謝謝@adrianbanks您的貢獻。 – griegs 2009-10-08 23:27:40

20

這是我成功

property.PropertyType.IsEnum 
0

這是我如何處理,當我轉換數據表到一個強類型列表

/// <summary> 
     /// Covert a data table to an entity wiht properties name same as the repective column name 
     /// </summary> 
     /// <typeparam name="T"></typeparam> 
     /// <param name="dt"></param> 
     /// <returns></returns> 
     public static List<T> ConvertDataTable<T>(this DataTable dt) 
     { 
      List<T> models = new List<T>(); 
      foreach (DataRow dr in dt.Rows) 
      { 
       T model = (T)Activator.CreateInstance(typeof(T)); 
       PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T)); 

       foreach (PropertyDescriptor prop in properties) 
       { 
        //get the property information based on the type 
        System.Reflection.PropertyInfo propertyInfo = model.GetType().GetProperties().Last(p => p.Name == prop.Name); 

        var ca = propertyInfo.GetCustomAttribute<PropertyDbParameterAttribute>(inherit: false); 
        string PropertyName = string.Empty; 
        if (ca != null && !String.IsNullOrWhiteSpace(ca.name) && dt.Columns.Contains(ca.name)) //Here giving more priority to explicit value 
         PropertyName = ca.name; 
        else if (dt.Columns.Contains(prop.Name)) 
         PropertyName = prop.Name; 

        if (!String.IsNullOrWhiteSpace(PropertyName)) 
        { 
         //Convert.ChangeType does not handle conversion to nullable types 
         //if the property type is nullable, we need to get the underlying type of the property 
         var targetType = IsNullableType(propertyInfo.PropertyType) ? Nullable.GetUnderlyingType(propertyInfo.PropertyType) : propertyInfo.PropertyType; 
         // var propertyVal = Convert.ChangeType(dr[prop.Name], targetType); 
         //Set the value of the property 
         try 
         { 
          if (propertyInfo.PropertyType.IsEnum) 
           prop.SetValue(model, dr[PropertyName] is DBNull ? (object)null : Enum.Parse(targetType, Convert.ToString(dr[PropertyName]))); 
          else 
           prop.SetValue(model, dr[PropertyName] is DBNull ? (object)null : Convert.ChangeType(dr[PropertyName], targetType)); 
         } 
         catch (Exception ex) 
         { 
          //Logging.CustomLogging(loggingAreasType: LoggingAreasType.Class, loggingType: LoggingType.Error, className: CurrentClassName, methodName: MethodBase.GetCurrentMethod().Name, stackTrace: "There's some problem in converting model property name: " + PropertyName + ", model property type: " + targetType.ToString() + ", data row value: " + (dr[PropertyName] is DBNull ? string.Empty : Convert.ToString(dr[PropertyName])) + " | " + ex.StackTrace); 
          throw; 
         } 
        } 
       } 
       models.Add(model); 
      } 
      return models; 
     } 
相關問題