简体   繁体   English

具有动态类的C#反射

[英]c# reflection with dynamic class

I need to execute a method "FindAll" in my page. 我需要在页面中执行方法“ FindAll”。 This method returns a list of the object. 此方法返回对象列表。

This is my method that I execute "FindAll". 这是我执行“ FindAll”的方法。 FindAll requires an int and returns an List of these class. 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);
}

When I execute ObjectSource, it returns ok, but I can't access the result. 当我执行ObjectSource时,它返回ok,但是我无法访问结果。 In VS2008, I can visualize the list by "ctrl + Alt + q" but by casting doesn't work. 在VS2008中,我可以通过“ ctrl + Alt + q”来可视化列表,但强制转换不起作用。

I forgot to say: this method "FindAll" is static! 我忘了说:此方法“ FindAll”是静态的!

Few things going on here, first, your method doesn't return the result. 首先,您的方法不会返回结果。

Second, when you do return the object, there's nothing stopping you casting to the appropriate type in the calling code. 其次,当您返回对象时,没有什么可以阻止您在调用代码中强制转换为适当的类型。

Third, you could use Generics to make this method strongly typed like so: 第三,您可以使用泛型来使此方法的类型严格如下:

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

Try this (updated): 试试这个(更新):

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

A better solution would be to put your FindAll method into an interface -- say, IFindable , and make all your classes implement that interface. 更好的解决方案是将FindAll方法放入接口(例如IFindable ,并使所有类都实现该接口。 Then you can just cast the object to IFindable and call FindAll directly -- no reflection required. 然后,您可以将对象IFindableIFindable并直接调用FindAll -无需反射。

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

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

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