C#中如何获取调用方法的属性
我目前正在为我的应用程序编写一个错误记录器,基本上我感兴趣的是在处理异常时,我从我的日志记录类调用一个函数 CreateLogEntry(...) 。 我的想法是,我希望 CreateLogEntry(...) 知道它是从方法 BadFunction(...) 中调用的,并作为日志记录的一部分检索其参数过程。
现在我已经做了一些作业(虽然我想还不够:S),并且我确信我的解决方案位于 System.Reflection 中,并且已经找到了一些关于如何枚举类中所有函数的示例(http://www.csharp-examples.net/get-method-names/< /a>)。 但是是否有可能获得创建该异常的函数的名称。
例如(我得到的):
public string GetCurrentMode()
{
string currentMode = "";
try
{
currentMode = _host.Mode.ToString();
}
catch(Exception ex)
{
Common.MorpheeException me = new Common.MorpheeException();
me.MethodName = "GetCurrentMode";
me.NameSpace = "MorpheeScript";
me.ErrorNumber = 0;
me.ErrorDescription = ex.Message;
me.StackTrace = ex.StackTrace;
throw new FaultException<Common.MorpheeException>(me);
}
return currentMode;
}
我想要得到的:
public string GetCurrentMode()
{
string currentMode = "";
try
{
currentMode = _host.Mode.ToString();
}
catch(Exception ex)
{
Common.MorpheeException me = new Common.MorpheeException(ex);
// Here me should know that it is called from GetCurrentMode() and
// retrieve the parameters if there are any
throw new FaultException<Common.MorpheeException>(me);
}
return currentMode;
}
非常感谢您的帮助
I am currently writing an Error logger for my application, and basically what I am interested in, is when handling the exception, I invoke a function CreateLogEntry(...) from my logging class.
The idea is, I want CreateLogEntry(...) to know it was called from within a method BadFunction(...) and retrieve its parameters as part of the logging process.
Now I already did some homework (I guess not enough though :S), and I am sure my solution lies in the System.Reflection, and already found some examples on how to enumerate all functions within a class (http://www.csharp-examples.net/get-method-names/).
But would it be possible to get the name of the function that creating that exception.
Ex (what I got):
public string GetCurrentMode()
{
string currentMode = "";
try
{
currentMode = _host.Mode.ToString();
}
catch(Exception ex)
{
Common.MorpheeException me = new Common.MorpheeException();
me.MethodName = "GetCurrentMode";
me.NameSpace = "MorpheeScript";
me.ErrorNumber = 0;
me.ErrorDescription = ex.Message;
me.StackTrace = ex.StackTrace;
throw new FaultException<Common.MorpheeException>(me);
}
return currentMode;
}
What I want to have:
public string GetCurrentMode()
{
string currentMode = "";
try
{
currentMode = _host.Mode.ToString();
}
catch(Exception ex)
{
Common.MorpheeException me = new Common.MorpheeException(ex);
// Here me should know that it is called from GetCurrentMode() and
// retrieve the parameters if there are any
throw new FaultException<Common.MorpheeException>(me);
}
return currentMode;
}
Many thanks for your help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在
MorpheeException
构造函数中,您可以 使用反射查找调用方法 然后使用它。In
MorpheeException
constructior you can find calling method using reflection and then use it.