如何从Reflection中的ParameterInfo []中获取实际值

时间:2013-03-15 10:48:29

标签: c# .net reflection attributes

实际上我几乎没有什么问题可以更容易理解我要问的问题,我必须先显示我的代码。

public static void Main(string[] args)
{
    CustomClass customClass = new CustomClass();
    customClass.SomeMethod("asdas", true, 30.5);

}

public class CustomClass
{
    [MyAttribute]
    public Boolean SomeMethod(String a, Boolean b, Double c)
    {
        return true;
    }
}

public class MyAttribute : Attribute
{
    public MyAttribute()
    {
        SomeIntercepter.InterceptEverything();
    }
    public void DoSomethingBeforeMethodexecutes()
    {
      ....
    }
    public void DoSomethingAfterMethodExecutes()
    {
      ....
    }
}

public class SomeIntercepter
{
    public static void InterceptEverything()
    {
        StackTrace stackTrace = new StackTrace();
        var method = stackTrace.GetFrame(2).GetMethod();
        var parameters = method.GetParameters();
        if (parameters.Length > 3)
            return;

        String cacheKey = method.Name;

        for (int i = 0; i < parameters.Length; i++)
        {
            //HOW TO GET THE PARAMETER DATA ASSIGNED
            cacheKey += "_" + parameters[i];
        }
    }
}

所以我尝试做什么。我尝试在每次调用时拦截方法,并根据标有[MyAttribute]的方法的命令数据做一些事情。所以我通过StackTrace访问该方法,并尝试使用GetParameters获取所有的数据。 这是我的问题:      1)如何在InterceptEverything()中对SomeMethod的所有数据进行对象[]      2)如何在MyAttribute标记方法之前运行MyAttribute以运行方法DoSomethingBeforeMethodexecutes()      3)如何使用MyAttribute标记方法运行方法MyAttribute

DoSomethingAfterMethodexecutes()运行{{1}}

感谢您的任何建议。

1 个答案:

答案 0 :(得分:3)

您无法通过ParameterInfo从任何特定的框架中获取。该设施不存在。

另外:属性不执行。除非您使用的是postharp,否则它们只是信息。要让他们执行,您必须明确地编写反射代码来执行此操作。