jeudi 25 février 2016

use reflection to print its own method name, class library (portable)

I would like to use reflection for a method to print its own name. I have found similar question on different thread but their method does not seem to be applicable to my scenario. It was suggested to use

MethodBase.GetCurrentMethod().Name 

The complier error I got was "MethodBase" does not contain a definition for "GetCurrentMethod"

to get the current method own name but GetCurrentMethod does not exist in the portable class library in VS2015. Below is my code for your reference. Please note: some portable class library in version of VS earlier than 2015 may work, I have vs2015 and got the error.

namespace ClassLibrary1
{
    public sealed class Class1
    {
        public delegate int myFunction(object o);
        public Dictionary<string, myFunction> list = new Dictionary<string, myFunction>();
        private static readonly Class1 _instance = new Class1();
        static Class1()
        {
        }
        public Class1()
        {
            string[] n = { "f1", "f2" };
            MethodInfo mInfo;
            foreach (var i in n)
            {
                mInfo = typeof(Class1).GetTypeInfo().GetDeclaredMethod(i);
                ParameterExpression objExpr = Expression.Parameter(typeof(object));
                Expression<myFunction> expr = Expression.Lambda<myFunction>(Expression.Call(null, mInfo, objExpr), objExpr);
                list.Add(i, expr.Compile());
            }

            list.Add("f11", f1);
            list.Add("f21", f2);
        }
        public static Class1 Instance
        {
            get
            {
                return _instance;
            }
        }
        public static int f1(object o)
        {
            string n = MethodBase.GetCurrentMethod().Name;
            System.Diagnostics.Debug.WriteLine("current function is {0} ", n);
            return 0;
        }
        public static int f2(object o)
        {
            string n = MethodBase.GetCurrentMethod().Name;
            System.Diagnostics.Debug.WriteLine("current function is {0} ", n);
            return 0;
        }
    }

}

Any thought?





Aucun commentaire:

Enregistrer un commentaire