【发布时间】:2019-03-11 10:28:01
【问题描述】:
public partial class ReturnHeader
{
public int ReturnHeaderId { get; set; }
public int CustomerId { get; set; }
public string InvoiceNo { get; set; }
public virtual Customer Customer { get; set; }
public virtual ICollection<ReturnDetail> ReturnDetails { get; set; }
}
public void TraverseThroughClass<T> (T entity) where T : class
{
try
{
var type = typeof(T);
PropertyInfo[] props = type.GetProperties();
foreach (PropertyInfo prop in props)
{
if (typeof(IEnumerable).IsAssignableFrom(prop.PropertyType))
{
此检查确定属性是否为列表。
问题 1:如果为真,则将其转换为列表或任何集合。 我想要做的是,如果属性是一个集合,则对它进行转换,并为转换集合中的每个项目调用
TraverseThroughClass
/* Error casting into any collection*/
//var propertiesValues = prop.GetValue(entity) as IList;
var listType = GetCollectionItemType(prop.PropertyType);
foreach (var listItem in propertiesValues)
{
问题 2:对于集合中的每个项目调用 TraverseThroughClass(T 实体)
}
}
else
{
Console.WriteLine("Prop Name : " + prop.Name + " Prop Value : "
+ prop.GetValue(entity, null));
}
}
}
catch (Exception e)
{
throw;
}
}
public static Type GetCollectionItemType(Type collectionType)
{
var types = collectionType.GetInterfaces()
.Where(x => x.IsGenericType
&& x.GetGenericTypeDefinition() == typeof(IEnumerable<>))
.ToArray();
return types.Length == 1 ? types[0].GetGenericArguments()[0] : null;
}
【问题讨论】:
-
一个
string是一个IEnumerable<Char>。你觉得这很奇怪吗? -
我不像你@Damien_The_Unbeliever 那样是专家。谢谢你顺便告诉我。我会更新问题。
-
comparedEntityHashSets.Add(entity.GetHashCode());- 闻起来很香。允许不同的实体具有相同的哈希码。为什么不直接将entity添加到 HashSet 中? -
我会删除它。忽略那部分。
-
我实际上并不清楚这里的问题是什么。例如,我在您的问题中没有看到一个问号。
标签: c# asp.net-mvc entity-framework generics reflection