开发者

Get object function using reflection

I know how to get the properties using reflection but how would you get the function name and type of a property:

For Example: Combobox.Items.Add

I would like to get the info. for "Add开发者_StackOverflow" with reflection. Is this possible in .Net?


I would like to get the info. for "Add" with reflection. Is this possible in .Net?

Yes.

Just use Type.GetMethod. So, here you'd have to say:

var addMethodInfo = typeof(ObjectCollection).GetMethod("Add");

I'm using the fact that ComboBox.Items is of type System.Windows.Forms.ComboBox.ObjectCollection.


You can use Reflection to get a MethodInfo object that describes the method:

MethodInfo[] method = Combobox.Items.GetType().GetMethods();

Once you have this, you can use the methods and properties of MethodInfo to access and view information about the method.

To get the parameters that this method receives:

        MethodInfo[] method = Combobox.Items.GetType().GetMethods();

       // equivalent to previous code.
       // MethodInfo[] method = typeof(ObjectCollection).GetMethods();

        MethodInfo someMethod = method[0];

        ParameterInfo[] parameters = someMethod.GetParameters();


If you need to get all methods of a given object try

MethodInfo[] MI = Combobox.Items.GetType().GetMethods ();
// you can then loop over MI and access the method name for example MI[0].Name or even Invoke the method etc.
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜