How to find out which function was called

I use a delegate to dynamically choose between many ie functions

delegate bool CtrlTransfer(int xferLength, ref byte[] buffer); bool CtrlRead(int xferLength, ref byte[] buffer) { /* do a read */ } bool CtrlWrite(int xferLength, ref byte[] buffer) { /* do a write */ } 

and they are used in the dispatch function as

 byte[] RunTest(CtrlTransfer ctrlXferFunction, /* a bunch of other args */) { /* do some stuff */ ctrlXferFunction(/* its arguments */); /* do some more stuff */ return someByteArray; } 

The reason I'm using a delegate, rather than some kind of argument specifying the direction, is because ctrlXferFunction is called many times, and using if {..} else {..} gets really tedious everywhere.

Now my problem is that I do not know which control transfer function was actually called. If I try if(ctrlXferFunction == CtrlRead) a la Python or JavaScript, I get an error message that == cannot be used between the group of methods and CtrlTransfer.

Is there any way to find out which function was actually called?

(My apologies if I made any terminological errors. I'm new to C #)

+4
source share
2 answers

You can use the Method property for the delegate:

 if( ctrlXferFunction.Method.Name == "CtrlRead" ) ... 
+3
source

If I were in you, I would use an interface, not a delegate. This will lead to an easier search for information about what the caller is.

 interface IMyInterface { bool CtrlTransfer(int xferLength, ref byte[] buffer); } 

Then:

 class MyReader : IMyInterface { bool CtrlTransfer(int xferLength, ref byte[] buffer) { // do the read... } } 

Finally:

 var reader = ctrlXferInstance as MyReader; if (reader != null) { // ... } 
+1
source

Source: https://habr.com/ru/post/1487801/


All Articles