代码之家  ›  专栏  ›  技术社区  ›  Aran Mulholland JohnnyAce

在debug.assert语句中插入行号

  •  2
  • Aran Mulholland JohnnyAce  · 技术社区  · 14 年前

    我们使用 Debug.Assert 向开发人员发出代码问题的信号。我想添加发生错误的行号,但不硬编码,因为这可能会改变,我们将忘记更新字符串。

    添加错误的行号会很方便。有什么想法吗?

    4 回复  |  直到 8 年前
        1
  •  8
  •   Chris Schmich    14 年前
    Debug.Assert

    alt text

    __FILE__ __LINE__ StackTrace

    using System.Diagnostics;
    
    namespace Managed
    {
        class Program
        {
            static void Main(string[] args)
            {
                AssertWithCallSite(false, "Failed!");
            }
    
            [Conditional("DEBUG")]
            static void AssertWithCallSite(bool condition, string message)
            {
                if (!condition)
                {
                    var callSite = (new StackTrace(1, true)).GetFrame(0);
    
                    string fileName = callSite.GetFileName();
                    int lineNumber = callSite.GetFileLineNumber();
    
                    string assertMessage = string.Format(
                        "Assert at {0}:{1}:\n{2}",
                        fileName,
                        lineNumber,
                        message
                    );
    
                    Debug.Assert(false, assertMessage);
                }
            }
        }
    }
    
        2
  •  2
  •   Edward Leno    14 年前

    Whats the equivalent of LINE and FILE in C#

    string currentFile=new System.Diagnostics.StackTrace(true).GetFrame(0).GetFileName(); 
    int currentLine = new System.Diagnostics.StackTrace(true).GetFrame(0).GetFileLineNumber();  
    

        3
  •  1
  •   Dennis    14 年前

    StackTrace StackFrame System.Diagnostics

    static string GetDiagnosticsInformationForCurrentFrame()
    {
        StackTrace st = new StackTrace(new StackFrame(true));        
        StackFrame sf = st.GetFrame(1); // we want the frame from where this method was called
    
        return String.Format("File: {0}, Method: {1}, Line Number: {2}, Column Number: {3}", sf.GetFileName(), sf.GetMethod().Name, sf.GetFileLineNumber(), sf.GetFileColumnNumber());
    }
    

    Debug.Assert(true, "Unexpected error occurred at " + GetDiagnosticsInformationForCurrentFrame());
    

    Conditional GetDiagnosticsInformationForCurrentFrame

        4
  •  1
  •   Aran Mulholland JohnnyAce    8 年前

    UAP

     public static void Assert(bool val, string message,  [CallerFilePath] string file = "",  [CallerMemberName] string memberName = "", [CallerLineNumber] int lineNumber = 0)
        {
            string msg = String.Format($"File: {file}, Method: {memberName}, Line Number: {lineNumber}\n\n{message}");
            Debug.Assert(val, msg);
    
    
        }