代码之家  ›  专栏  ›  技术社区  ›  blu

基于类型将对象转换为IList<t>

  •  5
  • blu  · 技术社区  · 15 年前

    我正在尝试一个小的反省,并有一个关于如何将结果对象转换为IList的问题。

    下面是反映:

    private void LoadBars(Type barType)
    {
        // foo has a method that returns bars
        Type foo = typeof(Foo);
    
        MethodInfo method = foo.GetMethod("GetBars")
            .MakeGenericMethod(bar);
    
        object obj = method.Invoke(foo, new object[] { /* arguments here */ });
        // how can we cast obj to an IList<Type> - barType
    }
    

    如何将method.invoke的结果从BarType参数转换为类型为的IList?

    5 回复  |  直到 14 年前
        1
  •  5
  •   Jon Skeet    15 年前

    强制转换的要点通常是告诉编译器您有一些额外的信息—您知道 编译时间 . 你不知道这里的信息-你只知道 执行时间 .

    在铸造后,您希望如何处理该值?不可否认 一些 当你必须使用泛型接口时,即使你想得到不需要类型参数的成员(例如 Count 在里面 IList<T> )然而,如果这不是你想做的,如果你能提供更多的信息的话,这会很有帮助。

        2
  •  4
  •   user23462    14 年前

    我刚解决完这个问题。
    如果为true,则不能将对象强制转换为泛型IList,但可以通过调用列表对象的“toArray”方法将其转换为强类型数组。

    从另一个博客窃取解决方案。 http://amazedsaint.blogspot.com/2008/04/creating-generic-list-at-runtime.html

    toArrayMethod=obj.getType().getMethod(“toArray”);

    system.array StronglyTypeDarray=(system.array)到ArrayMethod.invoke(obj,空);

        3
  •  0
  •   bjornhol    15 年前

    在.net 4.0中,可以使用表达式树来实现这一点。

        4
  •  0
  •   Greg    15 年前
    private void LoadBars<T>()
    {
        Type barType = typeof(T);
        // foo has a method that returns bars
        Type foo = typeof(Foo);
    
        MethodInfo method = foo.GetMethod("GetBars")
            .MakeGenericMethod(bar);
    
        IList<T> obj = (IList<T>)method.Invoke(foo, new object[] { /* arguments here */ });
    }
    
        5
  •  0
  •   Radu094    15 年前

    只有当函数的调用方 条形码 在编译时,而不是 运行时 . 一旦这是真的,你就可以把函数模板化为:

    private IList<T> LoadBars<T>()
    {
    ...
    return obj as IList<T>;
    }