![](/img/trans.png)
[英].NET Reflection - How to get “real” type from out ParameterInfo
[英]How to get real value from the ParameterInfo[] in Reflection
實際上,我有幾個問題可以更容易地理解我在問什么我必須先展示我的代碼。
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
的所有SomeMethod
數據進行對象 [] 2) 如何在使用MyAttribute
標記的方法之前運行MyAttribute
以運行方法DoSomethingBeforeMethodexecutes()
3) 如何要說到MyAttribute
與標記方法后運行MyAttribute
運行方法DoSomethingAfterMethodexecutes()
感謝您的任何建議。
您無法通過ParameterInfo
從任何特定幀獲取值。 該設施不存在。
另外:屬性不執行。 除非您使用 postsharp 之類的東西,否則它們只是信息。 要讓它們執行,您必須顯式編寫反射代碼來執行此操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.