How do I use .NET reflection to get a list of properties that are of a particular class, including generic lists, e.g. I have a class that looks like this:
class Test
{
[NotConditional()]
[Order( 1 )]
public Value Name { get; set; }
[NotConditional()]
[Order( 2 )]
public Value Address { get; set; }
[NotConditional()]
[Order( 3 )]
public List<Value> Contacts { get; set; }
}
I want to get the Name, Address and Contacts properties as all of them are of type Value.
I have the following code, which works great, but I want the List<> bit to only pick up List<Value> properties.
var props = from p in this.GetType().GetProperties()
where p.PropertyType.IsSubclassOf( typeof( Std ) ) ||
( p.PropertyType.IsGenericType &&
p.PropertyType.GetGenericTypeDefinition() == typeof( List<> ) )
select new { Property = p };
I have tried:
var props = from p in this.GetType().GetProperties()
where p.PropertyType.IsSubclassOf( typeof( Std ) ) ||
( p.PropertyType.IsGenericType &&
p.PropertyType.GetGenericTypeDefinition() == typeof( List<Value> ) )
select new { Property = p };
But, it doesn't pick up any List<Value> properties and only picks up Name and Address properties.
** UPDATE **
I have included these two classes as well as I also want to include properties that also derive from Std'.
class Std
{
public int id { get; set; }
}
class Value : Std
{
public string Val { get; set; }
}
List<Value>properties I also wanted.GetGenericTypeDefinition.GetGenericTypeDefinitionmethod call.