开发者

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 | BindingF开发者_如何学Pythonlags.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, i got a few object that i need to bind a grid view and this list more than 1.000 records, then a want to pagging by 50, and this Object Source must be generic because will call FindAll of the classes!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜