【发布时间】:2012-03-01 17:02:35
【问题描述】:
我需要将一个对象转换为一个泛型集合,看:
var currentEntityProperties = currentEntity.GetType().GetProperties();
foreach (var currentEntityProperty in currentEntityProperties)
{
if (currentEntityProperty.PropertyType.GetInterfaces().Any(
x => x.IsGenericType &&
x.GetGenericTypeDefinition() == typeof(ICollection<>)))
{
var collectionType = currentEntityProperty.PropertyType.GetInterfaces().Where(
x => x.IsGenericType &&
x.GetGenericTypeDefinition() == typeof(ICollection<>)).First();
var argumentType = collectionType.GetGenericArguments()[0];
// now i need to convert the currentEntityProperty into a collection, something like that (this is wrong, so, what is thr right way?):
var currentCollection = (ICollection<argumentType.GetType()>)currentEntityProperty.GetValue(currentEntity, null);
}
}
我该怎么做?
Obs:我需要用这个集合调用另一个集合的 except 方法(这个集合我使用与 currentCollection 相同的方式获得,使用 anotherEntityProperty.GetValue(anotherEntity, null))
var itens = currentCollection.Except(anotherCollection);
【问题讨论】:
-
之后你打算用它做什么?如果您能告诉我们更多关于更广泛背景的信息,我们或许可以提供另一种方法。
-
你也不知道
anotherCollection的类型吗?你从哪里得到的?你能在早些时候用反射进行一个通用调用吗?如果您使用的是 C# 4,动态类型也可以使这更容易。 -
anotherCollection 的类型我也不知道,但我知道 currentCollection 和 anotherCollection 将具有相同的类型。我得到另一个集合的方式与我得到 currentCollection 的方式相同。
var anotherCollection = newEntityProperty.GetValue(newEntity, null);. -
@ViniciusOttoni 既然您显然精通反射,为什么不使用反射调用该方法?
-
@phoog 你的意思是,用反射调用 except 方法?
标签: c# reflection collections casting