我的很多C#代码遵循这种模式:
void foo(string param1, string param2, string param3)
{
try
{
// do something...
}
catch(Exception ex)
{
LogError(String.Format("Error in foo(param1={0}, param2={1}, param3={2}), exception={3}", param1, param2, param3, ex.Message));
}
}
Run Code Online (Sandbox Code Playgroud)
有没有办法在.NET中获取函数的键/值列表,以便我可以调用另一个函数来构造我的错误记录字符串?或者你有更通用/更好的方法吗?
我在谈论托管的.NET代码.如果我们运行任何程序并将VS附加到它,我们可以看到调用堆栈中每个方法的参数值.我想创建一个日志记录解决方案,它将记录调用堆栈中每个方法的所有参数值.实际上我需要这个信息,以防发生异常.
我知道可以通过分析API来实现.但我想知道只有托管代码才有可能吗?
更新:好的,可能使用纯.NET,这是不可能的.然后可能有某种非托管代码......重点是从应用程序本身内部执行此操作.在异常的情况下,应用程序可以调用某个库(可能是非托管的),它返回有关调用堆栈中方法值的信息.只是想一想......
想象一下,你在这个课程中得到了这个方法:
float Do(int a_,string b_){}
Run Code Online (Sandbox Code Playgroud)
我正在尝试做这样的事情:
float Do(int a_, string b_)
{
var params = GetParamsListOfCurrentMethod(); //params is an array that contains (a_ and b_)
}
Run Code Online (Sandbox Code Playgroud)
有人可以帮忙吗?
我为什么要这样做?
想象一下,你有一个接口:
public Interface ITrucMuch
{
float Do(int a_,string b_);
// And much more fct
}
Run Code Online (Sandbox Code Playgroud)
还有很多实现该接口的类
还有一个特殊的类,它也实现了接口:
public class MasterTrucMuch : ITrucMuch
{
public floatDo(int a_, string b_)
{
ITrucMuch tm = Factory.GetOptimizedTrucMuch(); // This'll return an optimized trucMuch based on some state
if(tm != null)
{
return tm.Do(a_,b_);
}
else
{ …Run Code Online (Sandbox Code Playgroud) 在方法调用中,我需要在堆栈中"跳转"三层并检索传递给该方法的参数的类型和值.获取参数类型很简单,但我找不到将值传递给堆栈上的某个方法的方法.
var st = new StackTrace();
var frames = st.GetFrames();
var methodParameters = frame[2].GetMethod().GetParameters;
// get each parameter value
Run Code Online (Sandbox Code Playgroud)
注意:使用StackTrace不是强制性的.
有没有办法在运行时找到传递给方法的参数值?