我如何使用.NET反射来获取特定类的属性列表,包括通用列表,例如,我有一个看起来像这样的类:
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; }
}
我想要得到的Name
,Address
并且Contacts
性能个个都是类型Value
。
我有以下代码,效果很好,但我只想了解List<>
一下List<Value>
属性。
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 };
我试过了:
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 };
但是,它不选择任何List<Value>
属性,而仅选择Name
和Address
属性。
** 更新 **
我不仅包括了这两个类,而且还希望包括也从Std
'派生的属性。
class Std
{
public int id { get; set; }
}
class Value : Std
{
public string Val { get; set; }
}
似乎很简单。试试这个:
var props = from p in this.GetType().GetProperties()
where p.PropertyType == typeof(Value) ||
p.PropertyType == typeof(List<Value>)
select new { Property = p };
或处理Value
或的子类List<Value>
var props = from p in this.GetType().GetProperties()
where typeof(Value).IsAssignableFrom( p.PropertyType ) ||
typeof(List<Value>).IsAssignableFrom( p.PropertyType )
select new { Property = p };
鉴于你的更新,如果你想获得其类型是分配任何财产Std
或为一个列表,它的参数是分配的Std
,这是一个有点难度,因为List<T>
是不变的关于T
。如果那是您想要的,则可以执行以下操作:
var props = from p in this.GetType().GetProperties()
where typeof(Std).IsAssignableFrom( p.PropertyType ) ||
( p.PropertyType.IsGenericType &&
p.PropertyType.GetGenericTypeDefinition() == typeof(List<>) &&
typeof(Std).IsAssignableFrom( p.PropertyType.GetGenericArguments()[0] ) )
select new { Property = p };
请注意,此版本不返回其类型继承自的属性List<Std>
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句