Overloading function call operator in C#

前端 未结 7 495
北荒
北荒 2020-12-01 13:56

Is it possible to overload the default function operator (the () operator) in C#? If so - how? If not, is there a workaround to create a similar affect?

Thanks,

7条回答
  •  生来不讨喜
    2020-12-01 14:35

    You mention that you want to do logging, here is how you could do that with delegates:

    FooBar MyAlgorithm(Foo paramA, Bar paramB, Actions logger) {
        logger("Starting algorithm.")
        FooBar result = ...;
        logger("Finished algorithm.");
        return result;
    }
    

    When you run this you could log to the console:

    MyAlgorithm(a, b, (text) => Console.WriteLine(text));
    

    Or log to a Windows Forms TextBox:

    TextBox logbox = form.GetLogTextBox();
    MyAlgorithm(a, b, (text) => logbox.Text += text + Environment.NewLine);
    

提交回复
热议问题