Can I get parameter names/values procedurally from the currently executing function?

后端 未结 6 1380
猫巷女王i
猫巷女王i 2020-12-02 14:38

I would like to do something like this:

public MyFunction(int integerParameter, string stringParameter){
    //Do this:
    LogParameters();
    //Instead of         


        
6条回答
  •  臣服心动
    2020-12-02 14:55

    This is the Utility class that creates the log.

    internal class ParamaterLogModifiedUtility
    {
        private  String _methodName;
        private String _paramaterLog;
    
        private readonly JavaScriptSerializer _serializer;
        private readonly Dictionary _methodParamaters;
        private readonly List>_providedParametars;
    
        public ParamaterLogModifiedUtility(params Expression>[] providedParameters)
        {
            try
            {
                _serializer = new JavaScriptSerializer();
                var currentMethod = new StackTrace().GetFrame(1).GetMethod();
    
                /*Set class and current method info*/
                _methodName = String.Format("Class = {0}, Method = {1}", currentMethod.DeclaringType.FullName, currentMethod.Name);
    
                /*Get current methods paramaters*/
                _methodParamaters = new Dictionary();
                (from aParamater in currentMethod.GetParameters()
                 select new { Name = aParamater.Name, DataType = aParamater.ParameterType })
                 .ToList()
                 .ForEach(obj => _methodParamaters.Add(obj.Name, obj.DataType));
    
                /*Get provided methods paramaters*/
                _providedParametars = new List>();
                foreach (var aExpression in providedParameters)
                {
                    Expression bodyType = aExpression.Body;
    
                    if (bodyType is MemberExpression)
                    {
                        AddProvidedParamaterDetail((MemberExpression)aExpression.Body);
                    }
                    else if (bodyType is UnaryExpression)
                    {
                        UnaryExpression unaryExpression = (UnaryExpression)aExpression.Body;
                        AddProvidedParamaterDetail((MemberExpression)unaryExpression.Operand);
                    }
                    else
                    {
                        throw new Exception("Expression type unknown.");
                    }
                }
    
                /*Process log for all method parameters*/
                ProcessLog();
    
            }
            catch (Exception exception)
            {
                throw new Exception("Error in paramater log processing.", exception);
            }
        }
    
        private void ProcessLog()
        {
            try
            {
                foreach (var aMethodParamater in _methodParamaters)
                {
                    var aParameter =
                        _providedParametars.Where(
                            obj => obj.Item1.Equals(aMethodParamater.Key) && obj.Item2 == aMethodParamater.Value).Single();
                    _paramaterLog += String.Format(@" ""{0}"":{1},", aParameter.Item1, _serializer.Serialize(aParameter.Item3));
                }
                _paramaterLog = (_paramaterLog != null) ? _paramaterLog.Trim(' ', ',') : string.Empty;
            }
            catch (Exception exception)
            {
                throw new Exception("MathodParamater is not found in providedParameters.");
            }
        }
    
        private void AddProvidedParamaterDetail(MemberExpression memberExpression)
        {
            ConstantExpression constantExpression = (ConstantExpression) memberExpression.Expression;
            var name = memberExpression.Member.Name;
            var value = ((FieldInfo) memberExpression.Member).GetValue(constantExpression.Value);
            var type = value.GetType();
            _providedParametars.Add(new Tuple(name, type, value));
        }
    
    
        public String GetLog()
        {
            return String.Format("{0}({1})", _methodName, _paramaterLog);
        }
    
    }
    

    Using the Utility

    class PersonLogic
    {
        public bool Add(PersonEntity aPersonEntity, ushort age = 12, String id = "1", String name = "Roy")
        {
            string log =  new ParamaterLogModifiedUtility(() => aPersonEntity, () => age, () => id, () => name).GetLog();
            return true;
        }
    }
    

    Now Calling the Usages

    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                PersonLogic personLogic = new PersonLogic();
                personLogic.Add(id: "1", age: 24, name: "Dipon", aPersonEntity: new PersonEntity() { Id = "1", Name = "Dipon", Age = 24 });
            }
            catch (Exception exception)
            {
                Console.WriteLine("Error.");
            }
            Console.ReadKey();
        }
    }
    

    Result Log:

            Class = MethodParamatersLog.Logic.PersonLogic, Method = Add("aPersonEntity":{"CreatedDateTime":"\/Date(1383422468353)\/","Id":"1","Name":"Dipon","Age":24}, "age":24, "id":"1", "name":"Dipon")
    

提交回复
热议问题