美文网首页
C#错误和异常之调用者信息

C#错误和异常之调用者信息

作者: 当我写下一亿行代码 | 来源:发表于2019-02-25 22:47 被阅读3次

    在处理错误时,希望能够获取到错误发生的位置信息。通过特性CallerLineNumber、CallerFilePath、CallerMemberName分别获知调用者的行数、文件路径以及调用成员。

    新建一个CallerInformationHelper类:

    using System;
    using System.Runtime.CompilerServices;
    
    namespace CallerInfomation
    {
        public class CallerInformationHelper
        {
            public void Log([CallerLineNumber] int line = -1,
                [CallerFilePath] string path = null,
                [CallerMemberName] string name = null)
            {
                Console.WriteLine((line < 0) ? "No line" : "Line" + line);
                Console.WriteLine((path == null) ? "No file path" : path);
                Console.WriteLine((name == null) ? "No member name" : name);
    
                Console.WriteLine();
            }
    
            private int someProperty;
            public int SomeProperty
            {
                get { return someProperty; }
                set
                {
                    this.Log();
                    someProperty = value;
                }
            }
            
        }
    }
    

    编写一些测试代码:

    using System;
    
    namespace CallerInfomation
    {
        class Program
        {
            static void Main(string[] args)
            {
                CallerInformationHelper helper = new CallerInformationHelper();
                helper.Log();
                helper.SomeProperty = 33;
    
                Action a1 = () => helper.Log();
                a1();
                
                Console.ReadLine();
            }        
        }
    }
    

    最后在控制台的输出如下:

    Line10
    E:\dotnet\Chapter16\CallerInfomation\Program.cs
    Main
    
    Line25
    E:\dotnet\Chapter16\CallerInfomation\CallerInformationHelper.cs
    SomeProperty
    
    Line13
    E:\dotnet\Chapter16\CallerInfomation\Program.cs
    Main
    

    不禁要思考一个问题,调用者信息如何使用到实际的代码中,以确定异常发生在哪一行。目前调试阶段是通过try-catch与pdb文件,编写形如以下代码的方式查看异常发生的信息:

    try
    {
        ...
    }
    catch(Exception ex)
    {
        //自定义一个日志记录方法
        LogRecord.Log(Class.Name,ex.ToString());
    }
    ···
    
    

    相关文章

      网友评论

          本文标题:C#错误和异常之调用者信息

          本文链接:https://www.haomeiwen.com/subject/spnnyqtx.html