如何获得的IDictionary<字符串,对象>称为在C#中的参数previous方法? [英] How to get a IDictionary<string, object> of the parameters previous method called in C#?

查看:512
本文介绍了如何获得的IDictionary<字符串,对象>称为在C#中的参数previous方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够得到一个的IDictionary&LT形式的参数列表,字符串,对象> 叫做previous方法。这里有一个陷阱:我不能使用第三方面向方面的编程框架,即使它是免费的。

I would like to be able to get a list of parameters in the form of a IDictionary<string, object> of the previous method called. There is one catch: I cannot make use of third-party Aspect Oriented Programming framework even when it's free.

例如:

using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace Question {
    internal class Program {
        public static void Main(string[] args) {
            var impl = new Implementation();
            impl.MethodA(1, "two", new OtherClass { Name = "John", Age = 100 });
        }
    }

    internal class Implementation {
        public void MethodA(int param1, string param2, OtherClass param3) {
            Logger.LogParameters();
        }
    }

    internal class OtherClass {
        public string Name { get; set; }
        public int Age { get; set; }
    }

    internal class Logger {
        public static void LogParameters() {
            var parameters = GetParametersFromPreviousMethodCall();
            foreach (var keyValuePair in parameters)
                Console.WriteLine(keyValuePair.Key + "=" + keyValuePair.Value);
                // keyValuePair.Value may return a object that maybe required to
                // inspect to get a representation as a string.
        }

        private static IDictionary<string, object> GetParametersFromPreviousMethodCall() {
            throw new NotImplementedException("I need help here!");
        }
    }
}

任何建议或想法?随意使用反射,如果有必要的。

Any suggestion or ideas? Feel free to use reflection if necessary.

推荐答案

您可以使用的 堆栈跟踪 得到你所需要的:

You could use StackTrace to get all you need:

var trace = new System.Diagnostics.StackTrace();
var frame = trace.GetFrame(1); //previous
var method = frame.GetMethod();

现在你有一个 MethodBase 的实例。

您可以通过获取名称:

var method = method.Name;

和参数由 MethodBase.GetParameters

例如:

var dict = new Dictionary<string, object>();
foreach (var param in method.GetParameters())
{
    dict.Add(param.Name, param.DefaultValue);
}

这篇关于如何获得的IDictionary&LT;字符串,对象&gt;称为在C#中的参数previous方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆