传递string时传递NullReference异常,传递string.Format(string)解析。帮助我理解这一点?

时间:2016-06-10 15:01:37

标签: c#

我有一个带有一些重载来处理日志记录的方法,并且注意到一些(对我而言)奇怪的行为。重载(在我的其他类继承的类中)生成一个堆栈跟踪并调用主日志记录方法,然后写出一条表面上包含调用类和方法的行:

class Global
{
    public static void LogLine(string logline, StackTrace st)
    {
        string cmethod = st.GetFrame(1).GetMethod().Name;
        string cclass = st.GetFrame(1).GetMethod().DeclaringType.Name;
        string logsuffix = String.Format(" ({0}.{1})", cclass, cmethod);
        string curDir = Directory.GetCurrentDirectory();
        string logfile = String.Format(@"{0}\logs\Logfile_{1}.log", curDir, DateTime.Today.ToString("yyyyMMdd"));
        using (System.IO.StreamWriter log = new System.IO.StreamWriter(logfile, true))
        {
            string curtime = String.Format("[{0}]: ", DateTime.Now.ToString("yyyyMMdd-HHmm"));
            log.WriteLine(curtime + logline + logsuffix);
        }
        return;
    }

    public static void WLog(string logline)
    {
        StackTrace st = new StackTrace();
        LogLine(logline, st);
    }

    public static void WLog(string logline, object obj0)
    {
        StackTrace st = new StackTrace();
        LogLine(string.Format(logline, obj0), st);
    }
}

现在奇怪的行为。这将生成一个空引用异常:

class Program : Global
    {
        static void Main(string[] args)
        {
            string text = "rando text";
            WLog(text);
        }
    }

如果我将字符串包装在WLog(string)中的string.Format中,它可以正常工作:

   public static void WLog(string logline)
    {
        StackTrace st = new StackTrace();
        LogLine(string.Format(logline), st);
    }

任何人都可以帮助我理解为什么会这样吗?

生成的异常:

Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
   at ...Global.LogLine(String logline, StackTrace st) in ...\Global.cs:line 15
   at ...Program.Main(String[] args) in ...\Program.cs:line 24

0 个答案:

没有答案