简体   繁体   English

C#类索引器方法调用(日志)

[英]C# class indexer method call (log)

I'm trying to implement my own solution for logging. 我正在尝试实现自己的日志记录解决方案。 Everything works fine except one thing, that just doesn't want to work out. 除了一件事,一切都工作正常,就是不想工作。 I have a class (Log), which has methods to log to file etc. I can use it like Log.Debug(message, args), but thats not enough for me. 我有一个类(Log),它具有记录文件等的方法。我可以像Log.Debug(message,args)一样使用它,但是那对我来说还不够。

Sadly in C# we can't overload the call operator to be able to do something like Log(message, args). 可悲的是,在C#中,我们无法使调用运算符过载,从而无法执行Log(message,args)之类的操作。 Therefore I've searched on the web and found out about the indexer. 因此,我已经在网上搜索了有关索引器的信息。 My idea would be now to do something like: 我的想法是现在要做类似的事情:

Log[loggingMode](message, args). Log [loggingMode](消息,参数)。

But I just can't get it working. 但是我就是无法正常工作。 I currently have delegate, a method and the indexer, which look like this: 我目前有委托,方法和索引器,如下所示:

    /// <summary>
    /// Delegate for logging function, used by the indexer.
    /// </summary>
    /// <param name="mode">The logging mode.</param>
    /// <param name="message">The message to log.</param>
    /// <param name="args">The args for the message (String.Format).</param>
    public delegate void LogDelegate(string mode, string message, params object[] args);

    public LogDelegate this[string mode]
    {
        get
        {
            return LogIndexer;
        }
    }

    public void LogIndexer(string mode, string message, params object[] args)
    {
        lock (_Lock)
        {
            _queue.Enqueue(new LogEntry(String.Format(message, args), mode));
        }
    }

Now my question is, how can I pass the one argument of the indexer (mode) to the function, so that I can call it like: 现在我的问题是,如何将索引器(模式)的一个参数传递给函数,以便可以这样调用它:

Log"debug"; 记录“调试”;

this[string mode] getter should use its mode parameter to return a lambda with this mode: this[string mode] getter应该使用其mode参数返回具有该模式的lambda:

public delegate void LogDelegate(string message, params object[] args);

public LogDelegate this[string mode]
{
    get
    {
        return (message, args) => LogIndexer(mode, message, args); 
    }
}

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

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