【问题标题】:Reflection, get collection of objects and convert these to desired object type反射,获取对象集合并将它们转换为所需的对象类型
【发布时间】:2014-06-16 11:45:31
【问题描述】:

所以.. 我有一些 WCF 服务,这些 wcf 服务是通过反射调用的。它们返回具有不同对象的数组,这些对象对于被调用的每个服务都是不同的。

我的任务是获取这些对象并将它们映射到我的 BusinessObjects 中的对象。它们由T 定义。

    public virtual IQueryable<T> GetAll()
    {
        //Methods retreives an array of objects.
        var blah = _getAllFromWcf.Invoke(_rawServiceObject, new object[] {});
        //Says that this is an array
        var blahsType = blah.GetType();
        //This is the type of object in the array
        var blahsElementType = blahsType.GetElementType();
        //This is where i want to convert the element in the array to the type T so that i can return it in the IQueryable<T>
        blah.MapCollection<'The type of element in blah', T>();

        return null;
    }

blah.MapCollection 是我制作的一种扩展方法,它使用 AutoMapper 并转换列表中的元素。

MapCollection 现在当然不能工作,因为它不理解 blah 是一个数组,并且“blah 中的元素类型”不工作,因为我现在不知道对象的类型。 ...

任何人有任何指导?

【问题讨论】:

  • 您可以继续使用反射和调用 MapCollection 方法:stackoverflow.com/questions/232535/…
  • 好主意..但我仍然需要将集合作为 IQueryable 返回...有什么提示吗?

标签: c# wcf reflection automapper system.reflection


【解决方案1】:

您的扩展方法不能使用该类型作为泛型参数,因为它在运行时未知。您必须将其作为Type 类型的普通参数传递给您的扩展程序。 AutoMapper 也提供了将类型信息作为普通参数传递的方法。

您也可以只使用 LinQ 与 AutoMapper 进行映射:

blah.Select(item => Mapper.Map(item, item.GetType(), typeof(T)) as T)

【讨论】:

  • 但是我仍然必须能够告诉 Automapper 它收到的对象是某种列表/数组/可枚举的对象,如果不是,它将尝试将其映射为单个对象,这将不工作..那我该怎么做?
  • @BjørnØyvindHalvorsen 不一定,你可以自己做容器转换,让automapper担心item到item的转换。请查看我的编辑。
  • 那太好了!谢谢你..我最终做的有点不同..我会发布我提出的解决方案.. :)
【解决方案2】:

我最终这样做了..如果你有 cmets,或者只是有更好的方法,请随时发表评论:)

    public virtual IQueryable<T> GetAll()
    {
        //Methods retreives an array of objects.
        var collectionFromWcfService = _getAllFromWcf.Invoke(_rawServiceObject, new object[] {});
        //Says that this is an array
        var typeOfArray = collectionFromWcfService.GetType();
        //This is the type of object in the array
        var elementTypeInArray = typeOfArray.GetElementType();

        MethodInfo method = typeof(Extensions).GetMethod("MapCollectionWithoutExtension");
        MethodInfo generic = method.MakeGenericMethod(elementTypeInArray,typeof(T));

        var convertedListOfObjects = (List<T>)generic.Invoke(this, new []{ collectionFromWcfService });

        return convertedListOfObjects.AsQueryable(); 
    }

有了这个解决方案,我隐藏了 AutoMapper 的实现,现在可以通过另一个工具进行转换,或者如果我以后需要它可以手动进行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-02
    • 1970-01-01
    相关资源
    最近更新 更多