0

我想用这样的日志函数创建 ac# 库:

class MyLogClass
{
    public void log(string format, params object[] args)
    {

        string message = string.Format(format, args);

        // custom function
        log_to_file(message); // or log_to_db() or log_to_txtBox()

    }
}

想法是根据需要更改函数,使用 log_to_file()、log_to_db() 或 log_to_txtBox()。

我正在考虑使用第三个参数(在格式之前)作为代表来表示自定义函数,但我不知道该怎么做。

4

1 回答 1

1

使用委托,您将编写如下内容:

class MyLogClass
{
    public static void Log(Action<string> outputAction, string format,
                           params object[] args)
    {
        string message = string.Format(format, args);
        outputAction(message);
    }
}

请注意,参数不能出现参数之后,args因为后者是参数数组(由params关键字表示) - 参数数组只能作为声明中的最后一个参数出现。

或者,您可以在创建类的实例时设置一个操作:

class MyLogClass
{
    private readonly Action<string> outputAction;

    public MyLogClass(Action<string> outputAction)
    {
        this.outputAction = outputAction;
    }

    public void Log(string format, params object[] args)
    {
        string message = string.Format(format, args);
        outputAction(message);
    }
}
于 2012-04-23T06:10:16.217 回答