【问题标题】:How to get a IDictionary<string, object> of the parameters previous method called in C#?如何获取在 C# 中调用的参数先前方法的 IDictionary<string, object>?
【发布时间】:2012-04-10 04:13:57
【问题描述】:

我希望能够以IDictionary&lt;string, object&gt; 的形式获取上一个调用方法的参数列表。有一个问题:即使是免费的,我也无法使用第三方面向方面的编程框架。

例如:

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!");
        }
    }
}

有什么建议或想法吗?如有必要,请随意使用反射。

【问题讨论】:

  • 这不需要反射;它需要一个调试器。

标签: c# .net reflection


【解决方案1】:

您可以使用StackTrace 来获得所需的一切:

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);
}

【讨论】:

【解决方案2】:

我认为如果没有 AOP,你能做的最好的事情就是使用 StackFrame 并获取被调用的方法。

我想这需要太多的开销。如果你传入一个你修改过的变量怎么办?在方法中修改原始值之前,您必须分配额外的空间来存储原始值。这可能很快就会失控

【讨论】:

  • 更不用说jit编译器可能内联方法。
猜你喜欢
  • 2012-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-29
  • 1970-01-01
  • 2017-11-27
  • 1970-01-01
相关资源
最近更新 更多