How to make a callback call in c #?
- oneWhat is callback in your understanding? What call syntax do you want? And what semantics? How many subscribers, how many call sources? Describe your task in more detail. - VladD
- Well transfer the subroutine as a parameter to another subroutine. For example in C ++: void do_action (int & x, void (* f) (int &)) {f (x); } in the main program: int i = 5; do_action (i, twice); where twice is a function that doubles the number of how to implement such a mechanism in C #? - rekrut
|
2 answers
It's simple:
C ++:
void do_action(int &x, void(*f)(int &)) { f(x); } int i = 5; do_action(i, twice); void twice(int &x) { x = 2 * x; }
C #:
public delegate F(ref int x); // как бы typedef void DoAction(ref int x, F f) { f(ref x); } void makeDouble(ref int x) { x = 2 * x; } int i = 5; DoAction(ref i, makeDouble);
Note that makeDouble
can be, in contrast to C ++, a non-static (!) Method.
For normal cases when your callback does not accept out
/ ref
arguments, there are delegates that are prepared, and almost always use them:
// Func<int, int> -- функция, принимающая int и возвращающая тоже int int Apply(int x, Func<int, int> f) { return f(x); } int getDouble(int x) { return 2 * x; } int i = 5; i = Apply(i, getDouble);
Or it can be easier with lambdas:
int i = 5; i = Apply(i, x => 2 * x);
|
Event?
I could be wrong, but I did something like this:
public class ArtDMXEventArgs : EventArgs { public IPAddress Sender; public uint Universe; public byte[] Data; } public delegate void ArtDMXHandler(object sender, ArtDMXEventArgs e); class ArtNetNode { public event ArtDMXHandler onArtDMX; // ... private void FireOnArtDMX(IPAddress Sender, uint Universe, byte[] Data) { if (onArtDMX == null) return; ArtDMXEventArgs e = new ArtDMXEventArgs(); e.Sender = Sender; e.Data = Data; e.Universe = Universe; onArtDMX(this, e); } // ... }
Client Code:
{ // Добавление обработчика Node.onArtDMX += new ArtDMXHandler(onArtDmx); } private void onArtDmx(object Sender, ArtDMXEventArgs e) { // Обработчик, вызывается по приходу пакета }
All callbacks, as far as I have met, are made according to such mechanics.
|