Is there a way to dynamically retrieve the names of the public methods for an Object?
Dynamically Retrieve Method Names
Collapse
X
-
RRRRRRRRReflect ion Power!
You can do it with Reflection
(gathering info, please wait...)
Its C#, but it's two lines
[code=C#]
//Get the Type for your object
Type t = myObject.GetTyp e();
//Invoke the .GetMembers() (or maybe .GetMethods)
MemberInfo[] mems = t.GetMember("So meNameOfMember" , BindingFlags.Pu blic );
//I have a public function called Start(), so I put in "Start" instead of "SomeNameOfMemb er"
[/code] -
Ok, I didn't see the Type.GetMethods () method because it wasn't being listed by the intellisense (doh).
Anyways, I keep getting back an array with the length of 0.
[code=vbnet]
Dim t As Type = GetType(FooBar)
Dim info() As MemberInfo = t.GetMethods 'Nothing's returned by this call
Dim str As New StringBuilder
For Each member As MemberInfo In info
str.Append(memb er.Name)
str.Append(vbLf )
Next
MessageBox.Show (str.ToString)[/code]Comment
-
Did you try this:
MemberInfo[] mems=t.GetMembe rs(BindingFlags .Public);
or I guess for you:
Dim mems() as MemberInfo = t.GetMembers(Bi ndingFlags.Publ ic)
I never had any trouble with:
[code=c#]
public static List<string> GetMemberNames( object ReflectedObject )
{
List<string> retval = new List<string>();
if (ReflectedObjec t != null)
{
MemberInfo[] mems = ReflectedObject .GetType().GetM embers();
foreach (MemberInfo mi in mems)
{
string name = mi.Name;
retval.Add(name );
}
}
return retval;
}
[/code]Comment
-
Getting the Methods for the String class works fine:
[code=vbnet]
Dim t As Type = GetType(String)
Dim info() As MemberInfo = t.GetMethods
Dim str As New StringBuilder
For Each member As MemberInfo In info
str.Append(memb er.Name)
str.Append(vbLf )
Next
MessageBox.Show (str.ToString)[/code]
It must have something to do with Interop.....hmm mComment
-
Well you never said anything about it being a COM object :-P
Interop are all Interface calls, you will have to change your binding flags
Edit: I think
I couldn't get the watch window to show members of a COM object (Say Excel.Applicati on) but the intellisense workedComment
-
The GetFields() method worked for the COM type though...I didn't think that there would be a problem with the GetMethods() method but apparently it doesn't like it.
Mind you this doesn't surprise me because even though the GetFields() method works the SetValue() (for the field) does not work....well not without casting the type into a ValueType first and then using the SetValue.Comment
-
I've tried all of the Bindings that deal with COM objects and still can't retrieve the methods.Comment
Comment