繁体   English   中英

具有动态类的C#反射

[英]c# reflection with dynamic class

我需要在页面中执行方法“ FindAll”。 此方法返回对象列表。

这是我执行“ FindAll”的方法。 FindAll需要一个int并返回这些类的List。

public void ObjectSource(int inicio, object o)
{
  Type tipo = o.GetType();
  object MyObj = Activator.CreateInstance(tipo);
  object[] args = new object[1];
  args[0] = inicio;
  List<object> list = new List<object>();
  object method = tipo.InvokeMember("FindAll", BindingFlags.Default | BindingFlags.InvokeMethod, null, null, args);
}

当我执行ObjectSource时,它返回ok,但是我无法访问结果。 在VS2008中,我可以通过“ ctrl + Alt + q”来可视化列表,但强制转换不起作用。

我忘了说:此方法“ FindAll”是静态的!

首先,您的方法不会返回结果。

其次,当您返回对象时,没有什么可以阻止您在调用代码中强制转换为适当的类型。

第三,您可以使用泛型来使此方法的类型严格如下:

public T ObjectSource<T>(int inicio, T o)
{
  Type tipo = typeof(T);
  object MyObj = Activator.CreateInstance(tipo);
  object[] args = new object[1];
  args[0] = inicio;
  return tipo.InvokeMember("FindAll", BindingFlags.Default | BindingFlags.InvokeMethod, null, null, args) as T; 
}

试试这个(更新):

public IEnumerable ObjectSource(int inicio, object o) {
    Type type = o.GetType();
    object[] args = new object[] { inicio };
    object result = type.InvokeMember("FindAll", 
        BindingFlags.Default | BindingFlags.InvokeMethod, null, o, args);
    return (IEnumerable) result;
}

更好的解决方案是将FindAll方法放入接口(例如IFindable ,并使所有类都实现该接口。 然后,您可以将对象IFindableIFindable并直接调用FindAll -无需反射。

丹尼尔(Daniel),我得到了一些需要绑定网格视图的对象,并且该列表列出了1.000多个记录,然后希望按50进行分页,并且该对象源必须是通用的,因为它将调用FindAll类!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM