.NET中是否有办法知道哪些参数及其值传递给方法。反思方式?这将在方法内部使用。它必须是通用的,因此可以从任何方法使用它。这是用于记录目的。
答案 0 :(得分:10)
MethodInfo.GetCurrentMethod()
会为您提供有关当前方法的信息,然后使用GetParameters()
获取有关参数的信息。
答案 1 :(得分:8)
致电MethodBase.GetCurrentMethod().GetParameters()
但是,无法获取参数值;由于JIT优化,它们甚至可能不再存在。
答案 2 :(得分:5)
使用面向方面的编程可以轻松实现您尝试做的事情。网上有很好的教程,我会指出其中两个:
答案 3 :(得分:1)
public void FunctionWithParameters(string message, string operationName = null, string subscriptionId = null)
{
var parameters = System.Reflection.MethodBase.GetCurrentMethod().GetParameters();
this.PrintParams(parameters, message, operationName, subscriptionId);
}
public void PrintParams(ParameterInfo[] paramNames, params object[] args)
{
for (int i = 0; i < args.Length; i++)
{
Console.WriteLine($"{paramNames[i].Name} : {args[i]}");
}
}
答案 4 :(得分:0)
您需要AOP才能实现所需的功能。 在C#中,您可以使用DispatchProxy来做到这一点。 检查以下How to wrap existing object instance into DispatchProxy?
答案 5 :(得分:0)
如今,Roslyn's Source Generators是可以用来实现此目的的功能。
这样,将在方法定义的基础上在编译时生成获取参数值的代码。可以解释为“ 编译时反射”。
让我们看一个例子来尝试更好地解释它:
public void MethodInspectingItsOwnParameters(
[Description("First parameter")]
string paramName_1,
[Description("Second parameter")]
int paramName_2,
// ...
[Description("N-th parameter")]
object paramName_N,
// ...
[Description("Last parameter")]
bool paramName_M)
{
var paramsAndValues = new List<KeyValuePair<string, object>>();
// -
// => Put here the code that, using Roslyn's compile time
// metaprogramming, inspect the parameters from the method
// definition and at compile time generate the code that
// at run time will get the parameters's values and load
// them into [paramsAndValues]
// -
// #Rosalyn generated code
// · Code autogenerated at compile time
// => loads parameter's values into [paramsAndValues]
// -
// Eg (Hypothetical example of the code generated at compile
// time by Roslyn's metaprogramming):
//
// paramsAndValues.Add("paramName_0", paramName_1);
// ...
// paramsAndValues.Add("paramName_N", paramName_N);
// ...
// paramsAndValues.Add("paramName_M", paramName_M);
//
// - Note: this code will be regenerated with each compilation,
// so there no make sense to do nameof(paramName_N)
// to obtaint parameter's name
// #End Rosalyn generated code
foreach (var param in paramsAndValues)
{
string paramName = param.Key;
object paramValue = param.Value;
// In this section of the normal code (not generated at
// compile time) do what you require with the
// parameters/values already loaded into [paramsAndValues]
// by the compile time generated code
}
}