2013-03-15 105 views
2

其实我有几个问题可以更容易理解我在问什么,我必须先显示我的代码。如何从反射中的ParameterInfo []中获得实际值

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)如何说来着MyAttributeMyAttribute运行标记之前方法运行方法DoSomethingBeforeMethodexecutes() 3)如何对MyAttribute运行标记后的方法运行MyAttribute运行方法DoSomethingAfterMethodexecutes()

感谢您的任何建议。

回答

2

您无法通过ParameterInfo从任何特定帧获取。这个设施不存在。

另外:属性不要执行。除非你使用类似postsharp的东西,否则它们只是信息。要让他们到执行您必须明确写入反射代码才能做到这一点。

+0

但是我怎样才能从StackTrace中获得它? – Maris 2013-03-15 10:51:12

+1

@Maris有一个你跳过的问题:*可以*我从StackTrace中获得它。答案是:不,你不能。 – 2013-03-15 10:52:09

+0

@Maris:你不能。你需要一个调试器或分析器来获取这些信息。 – leppie 2013-03-15 10:52:23

相关问题