Referencing a function in a variable?

后端 未结 4 1795
攒了一身酷
攒了一身酷 2021-01-11 23:42

Say I have a function. I wish to add a reference to this function in a variable.

So I could call the function \'foo(bool foobar)\' from a variable \'bar\', as if it

4条回答
  •  清酒与你
    2021-01-12 00:43

    You need to know the signature of the function, and create a delegate.

    There are ready-made delegates for functions that return a value and for functions that have a void return type. Both of the previous links point to generic types that can take up to 15 or so type arguments (thus can serve for functions taking up to that many arguments).

    If you intend to use references to functions in a scope larger than a local scope, you can consider defining your own custom delegates. But most of the time, Action and Func do very nicely.

    Update:

    Take a look at this question regarding the choice between defining your own delegates or not.

提交回复
热议问题