[Mono-devel-list] Re: Invoke..

Robert Wittams robert at wittams.com
Sun Jan 16 08:38:53 EST 2005


Auge Mike wrote:
> Hi guys,
> 
> I have a Q for you. If I have an array of objects, and each object is of 
> different class type. But all the classes implement a method with the 
> same name and sig. Note that the calsses dose no inherit from a shared 
> interface or class. Also the objects are casted to the class "object". 
> How can I invoke the method using the name in each object?
> 
> Thank you for your help in advance!
> 
> _________________________________________________________________
> Express yourself instantly with MSN Messenger! Download today it's FREE! 
> http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/

You'll need to use reflection. Standard "from memory" disclaimer applies.

Object[] objArray = ...;
foreach(object obj in objArray){
    Type t = obj.GetType();
    MemberInfo meth = t.GetMethod("MyFunc", BindingFlags.Public |
                 BindingFlags.Instance,
                 null,
                 CallingConventions.Any,
                 new Type[] {typeof(string),typeof(bool)},
                 null);
    meth.Invoke(obj, new Object[]{"inefficient",true});
}

But this is stupid. If you control the classes, make a one method 
interface. Alternatively, if the array is large but with few types, 
cache the method info for each type. I don't know at waht point this is 
worthwhile, the runtime may cache already. The invoke is always going to 
be slow.




More information about the Mono-devel-list mailing list