我已经通过反射得到类型实例。Type DllType = MyAssembly.GetType("MyClass");
Object DllObj = Activator.CreateInstance(DllType , null);
Type OtherType = MyAssembly.GetType("OtherClass");
MethodInfo DllMethod= DllType.GetMethod("DllMethod", new Type[] { OtherType });
Object objs = (Object)DllMethod.Invoke(DllObj, new Object[] { "AllObjects"});
这个返回的objs是一个ReadOnlyCollection<OtherClass>的集合,但是我怎么把objs这个Object类型变为ReadOnlyCollection<OtherClass>类型呢?
我试图用ReadOnlyCollection<Object> collect = ReadOnlyCollection<Object> objs强行转换,但不行。

解决方案 »

  1.   

    不好意思,这写错了,应该是:Type DllType = MyAssembly.GetType("MyClass");
    Object DllObj = Activator.CreateInstance(DllType , null);
    Type OtherType = MyAssembly.GetType("OtherClass");
    MethodInfo DllMethod= DllType.GetMethod("DllMethod", new Type[] { typeof(string)});
    Object objs = (Object)DllMethod.Invoke(DllObj, new Object[] { "AllObjects"});我怎么转换objs呢?
      

  2.   

    调试窗口中可以看到objs是一个object{System.Collections.ObjectModel.ReadOnlyCollection<OtherType>},但是我不能直接转换成ReadOnlyCollection<OtherType>,我现在怎么将这个objs转换为ReadOnlyCollection呢?或者怎么转换成其他的集合类型?
      

  3.   

    你的DllMethod是什么?怎么写的?返回类型是什么?
      

  4.   

    DllMethod是MyClass类中的一个方法,传递一个string,返回一个OtherClass对象的集合。
      

  5.   

    返回的是ReadOnlyCollection<OtherClass>类型。
    在C#中不是所有的Class都是继承自Object类的么?为什么ReadOnlyCollection<OtherClass>转换为ReadOnlyCollection<Object>会有错呢?
      

  6.   

    拜托,谁说泛型可以这样转啊……你不是转换成ReadOnlyCollection<OtherClass>出错么?到底是转换成什么出错!!我看您考虑先锻炼下表达能力。
      

  7.   

    OtherClass是在DLL中的一个类,我通过MethodInfo调用DLL中的方法可以的到ReadOnlyCollection<OtherClass>,但是这个ReadOnlyCollection<OtherClass>的是被封装成Object,我如何遍历这个Collection?
    这是我想要的。
      

  8.   

    ReadOnlyCollection.Count?
    有这个属性吗?有的话,FOR循环,没有的话,当我接分
      

  9.   

    //但是这个ReadOnlyCollection<OtherClass>的是被封装成Object
    这句话没看明白...
      

  10.   

    我也知道用Count最好了……
    但是ReadOnlyCollection<OtherClass>是被封装成Objec的,我不能把这个Object转成ReadOnlyCollection<OtherClass>,因为调用端不知道这个OtherClass,如果我用:
    ReadOnlyCollection<OtherClass> tempObjs = Objec as ReadOnlyCollection<OtherClass>会告诉你没有OtherClass这个类。
      

  11.   

    比如说:
    MethodInfo GetAllObjects = MyClassType.GetMethod("GetAllObjects ", new Type[] {typeof(string)});
    Object objs = (Object)DllMethod.Invoke(null, new Object[] { "AllObjects"});
    这个返回值objs是一个ReadOnlyCollection<OtherClass>的封装,但调用端没有定义这个OtherClass,我怎么去遍历它呢?
      

  12.   

    IList objs = (IList)DllMethod.Invoke(null, new Object[] { "AllObjects"});