Get Method Info - CSharp System.Reflection

CSharp examples for System.Reflection:MethodInfo

Description

Get Method Info

Demo Code


using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Reflection;
using System.ComponentModel;
using System.Collections.Generic;
using System;// w  ww .  ja  v a2 s  .c  om

public class Main{
        private static MethodInfo GetMethodInfo(object instance, string methodName, Type[] types = null, MethodAttributes attrs = MethodAttributes.Public) {
            if (instance == null) {
                throw new ArgumentNullException("instance");
            }
            if (String.IsNullOrEmpty(methodName)) {
                throw new ArgumentException("A method must be specified.", "methodName");
            }

            MethodInfo methodInfo;
            if (types != null) {
                methodInfo = instance.GetType().GetMethod(methodName,
                    BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
                    null,
                    types,
                    null);
            }
            else {
                methodInfo = instance.GetType().GetMethod(methodName,
                    BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            }

            if (methodInfo == null) {
                throw new ArgumentException(String.Format(
                    "A method named '{0}' on type '{1}' could not be found.",
                    methodName, instance.GetType().FullName));
            }

            if ((methodInfo.Attributes & attrs) != attrs) {
                throw new ArgumentException(String.Format(
                    "Method '{0}' on type '{1}' with attributes '{2}' does not match the attributes '{3}'.",
                    methodName, instance.GetType().FullName, methodInfo.Attributes, attrs));
            }

            return methodInfo;
        }
}

Related Tutorials