2011-03-29 57 views
1

我知道如何使用nlog将我的信息记录到文件中,但现在我想将我的日志重定向到ListView(C#)并执行一些操作。所以我把我的日志定向到文档nlog中解释的方法。有用。从静态方法中添加非静态对象中的元素?

<?xml version="1.0" ?> 
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
    <targets> 
     <target name="msgbox" xsi:type="MethodCall" className="SomeNamespace.MyClass, MyAssembly" methodName="LogMethod"> 
      <parameter layout="${level}" /> 
      <parameter layout="${message}" /> 
     </target> 
    </targets> 

    <rules> 
     <logger name="*" minlevel="Debug" writeTo="msgbox" /> 
    </rules> 
</nlog> 

Console.WriteLine的工作原理。这不是我的问题。

我想添加一行到我的logListView(见注释行),但我不能因为logListView不是静态的。怎么会这样?我如何继续?

回答

2

一个解决方案是为static成员添加到MyClass的,就像这样:

public class MyClass 
{ 
    public static ListView MyListView { get; set; } 

    public static void LogMethod(string level, string message) 
    { 
     Console.WriteLine("l: {0} m: {1}", level, message); 
     var logListView = MyListView; 
     if (logListView != null) { 
      logListView.Items.Add(Message); 
     } 
     // Do some other actions 
    } 
} 

您可以从您的应用程序的其他部分设置的MyListView值可用时。

虽然这种解决方案可行,但我不会喜欢它,因为它是违反直觉的。你在这里做的是在静态配置中声明一个在静态上下文中根本没有意义的日志目标:你想记录到一个尚未创建的UI控件,没有好的方法来引用它,直到应用程序的UI已被显示,并且UI将显示在点或(学术地说)可能根本不显示。

我相信最好创建自己的日志目标类,从TargetTargetWithLayout派生。您可以将任何必需的参数(例如ListView实例)传递给日志目标的构造函数,然后以编程方式在这些参数的值已知的位置添加日志目标(即显示UI并且我们可以引用ListView )。

+0

+1 a派生的'Target'在这些类型的场景中工作得很好。 – user7116 2011-03-29 14:06:46

相关问题