c# - 如何在泛型集合中转换对象?

标签 c# reflection collections casting

我需要将对象转换为通用集合,看:

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);

最佳答案

动态类型让您可以让编译器和 DLR 在这里完成所有工作:

dynamic currentCollection = ...;
dynamic anotherCollection = ...;
dynamic items = Enumerable.Except(currentCollection, anotherCollection);

在执行时,这将为您完成所有反射工作并选择最合适的类型参数。

关于c# - 如何在泛型集合中转换对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9520599/

相关文章:

c# - 传递无效主机名时 NTP 查询需要很长时间

java - Gson 反序列化为 List<Object>,其中列表的通用类型作为类名给出

scala - 使用 scala Type 设置类型参数(通过 TypeTag?)

java - 注释不可见?

java - 有序 map 实现

c# - 将启用分页的 GridView 导出到 Excel

c# - 在图像上绘制边框

c# - 限制 ListView 中的列大于 X(NotifyPropertyChanged 不起作用)

java - 如何按升序排序 ArrayList<Object> android

java - Vector or Synchronized LinkedList?哪个更好用?