简体   繁体   中英

c# reflection with dynamic class

I need to execute a method "FindAll" in my page. This method returns a list of the object.

This is my method that I execute "FindAll". FindAll requires an int and returns an List of these class.

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. In VS2008, I can visualize the list by "ctrl + Alt + q" but by casting doesn't work.

I forgot to say: this method "FindAll" is static!

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. Then you can just cast the object to IFindable and call FindAll directly -- no reflection required.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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