【发布时间】:2019-01-09 14:19:48
【问题描述】:
在我的解决方案中,我有一个业务验证服务,可以应用于任何具有实体类型基类的类。
现在我需要汇总被破坏但卡住的规则,我有可以是集合的属性,所以我还需要检查集合中的每个项目。
为此,我有这张支票
typeof(IEnumerable).IsAssignableFrom(property.PropertyType)
但现在我知道该类型是一个集合。
如何转换为该类型 IEnumerable<T> 以便我可以继续下一步。
这应该将检测到的集合中的项目作为第一个参数。
类似的东西
foreach(var collectionItem in collection)
{
AggregateBrokenRules(collectionItem, ref rules);
}
其中collection是转换或强制转换的结果
private void AggregateBrokenRules(Type reflectedType, ref List<BrokenRule> rules)
{
/// => don't apply any filter of any kind except for what already is provided
PropertyInfo[] properties = reflectedType.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
/// => iterate through discovered properties
foreach (PropertyInfo property in properties)
{
/// => if type is IEnumerable
if (typeof(IEnumerable).IsAssignableFrom(property.PropertyType))
{
/// => cast to IEnumerable
var propertyVal = Convert.ChangeType(types, property.PropertyType);
AggregateBrokenRules(property.PropertyType, ref rules);
}
/// => only properties that are of type Entity
if (typeof(Entity).GetTypeInfo().IsAssignableFrom(property.PropertyType))
{
/// => check next level
AggregateBrokenRules(property.PropertyType, ref rules);
}
/// => get the value from this property
object propertyValue = property.GetValue(reflectedType);
}
}
【问题讨论】:
-
您要检查财产的价值吗?当它是 IEnumerable 时,你想检查什么?
-
您是否希望获得
property.PropertyType.GetGenericArguments().First()? -
我不确定我需要做什么。我知道我需要得到什么。作为通用集合存储在属性中的值。所以我想我需要一个 IEnumerable
-
好吧,
property.PropertyType会给你IEnumerable<Something>,我第一条评论中的代码会给你Something。 -
如果您确定实现了
IEnumerable,请尝试强制转换(IEnumerable)propertyValue。
标签: c# .net reflection