2011-11-14 182 views
3

类别过滤器时使用Trace.Listener谁能告诉我,为什么Trace.Write(字符串,字符串)和Trace.WriteLine(字符串,字符串)不要

Trace.Write(string message, string category) 

未通过当方法

Trace.Write(object o, string category) 

将类别字符串传递给ShouldTrace方法时,将类别字符串添加到TraceFilter。下面是来自反射器的两种方法的反编译。只是想知道为什么.NET团队会在一种方法上做些什么,而不是另一种方法。

public virtual void Write(object o, string category) 
{ 
    if ((this.Filter == null) || 
this.Filter.ShouldTrace(null, "", TraceEventType.Verbose, 0, category, null, o)) 
    { 
     if (category == null) 
     { 
      this.Write(o); 
     } 
     else 
     { 
      this.Write((o == null) ? "" : o.ToString(), category); 
     } 
    } 
} 

然后字符串的方法。

public virtual void Write(string message, string category) 
{ 
    if ((this.Filter == null) || 
     this.Filter.ShouldTrace(null, "", TraceEventType.Verbose, 0, message)) 
    { 
     if (category == null) 
     { 
      this.Write(message); 
     } 
     else 
     { 
      this.Write(category + ": " + ((message == null) ? string.Empty : message)); 
     } 
    } 
} 
+0

我们如何知道原因?这两种方法使用两种不同的覆盖方式,这是不同行为的原因。 –

+0

嗯,我希望有人比我更了解这种不一致性。不过谢谢你的评论。 –

+0

措辞和格式化的问题 –

回答

0

在第一超负荷

this.Write((o == null) ? "" : o.ToString(), category); 

代表实际输出到this.Write呼叫转移到第二个重载

public virtual void Write(string message, string category) 

所有格式的输出是然后在第二集中过载:

this.Write(category + ": " + ((message == null) ? string.Empty : message)); 

通过以这种方式集中实际格式化,在单个位置更改格式将会更改所有跟踪输出格式。这是DRY principles的应用程序。