2017-03-03 59 views
2

我正在嘗試獲取對象的所有DateTime和Nullable < DateTime>屬性。我正在使用以下lamda表達式,但它返回0結果。這樣做的正確方法是什麼?在T obj中使用反射獲取所有DateTime和Nullable <DateTime>屬性使用反射

Type t = obj.GetType(); 

// Loop through the properties. 
PropertyInfo[] props = t.GetProperties() 
    .Where(p => p.GetType() == typeof(DateTime) || p.GetType() == typeof(Nullable<DateTime>)).ToArray(); 

回答

3

p.GetType()會給你這始終是PropertyInfop類型。相反,你應該使用p.PropertyType。例如:

Type t = obj.GetType(); 

//It's a little nicer to keep the types you're searching on 
//in a list and compare using Contains(): 
var types = new[] { typeof(DateTime), typeof(Nullable<DateTime>) }; 

PropertyInfo[] props = t.GetProperties() 
    .Where(p => types.Contains(p.PropertyType)) 
    .ToArray();