简体   繁体   English

如何通过不同的功能发送文本?

[英]how can I send text through different functions?

I want to create ac# library with a log function like this: 我想使用这样的日志功能创建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()

    }
}

The idea is to change the function as required, using log_to_file(), log_to_db() or log_to_txtBox(). 想法是使用log_to_file(),log_to_db()或log_to_txtBox()根据需要更改功能。

I was thinking of using a third parameter (before of format) as a delegate to represent a custom function, but I don't know how to do it. 我当时在考虑使用第三个参数(格式之前)作为代表自定义函数的委托,但是我不知道该怎么做。

Using a delegate, you'd write something like: 使用委托,您将编写如下内容:

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

Note that the parameter can't come after the args parameter, as the latter is a parameter array (as signified by the params keyword) - and a parameter array can only appear as the final parameter in a declaration. 请注意,参数不能 args参数之后,因为后者是参数数组 (由params关键字表示)-参数数组只能作为声明中的最终参数出现。

Alternatively, you could set an action when you create an instance of the class: 另外,您可以在创建类的实例时设置操作:

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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM