开发者

How to get the calling method properties in c# [duplicate]

This question already has answers here: How do I get the calling method name and type using reflection? [duplicate] (5 answers) Closed 3 years ago.

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.MorpheeExc开发者_JAVA百科eption();

            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


In MorpheeException constructior you can find calling method using reflection and then use it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜