Overloading function call operator in C#

前端 未结 7 489
北荒
北荒 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:39

    No, () isn't an operator so it cannot be overloaded. (This is incorrect, please see Eric Lippert's comment below) The parentheses are part of C#'s syntax that are used to express a set of arguments that are passed to a method. () simply indicates that the method in question specified no formal parameters and therefore requires no arguments.

    What are you trying to do? Perhaps if you gave a small example of the problem we would be able to help with a solution.

    Edit: Okay I see what you are getting at now. You could always create a delegate that maps to the method on the instance like this (given that class A defines a method like this: public void Foo() { }):

    Action action = someA.Foo;
    

    Then you could invoke the delegate with a simple syntax like this:

    action();
    

    Unfortunately (or not, depending on your preference) this is pretty much as close as C# will let you get to this kind of syntax.

提交回复
热议问题