Does C # support the __call__ method?

Python has this magic __call__ method, which is called when the object is called as a function. Does C # support something like this?


In particular, I was hoping you could use delegates and objects interchangeably. An attempt to develop an API in which the user can pass a list of functions, but sometimes these functions need some initial parameters, in which case they will use one of these called objects.

+4
source share
3 answers

Of course, if you inherit DynamicObject . I think you are after TryInvoke , which runs on obj(...) , but there are several other methods that you can override to handle castings, index access ( obj[idx] ), method calls, property calls, etc. d.

 using System; using System.Diagnostics; using System.Dynamic; using System.Linq; using System.Text; namespace ConsoleApplication { public static class ConsoleApp { public static void Main() { dynamic x = new MyDynamicObject(); var result = x("awe", "some"); Debug.Assert(result == "awesome"); } } public class MyDynamicObject : DynamicObject { public override Boolean TryInvoke(InvokeBinder binder, Object[] args, out Object result) { result = args.Aggregate(new StringBuilder(), (builder, item) => builder.Append(item), builder => builder.ToString()); return true; } } } 
+5
source

I bow to Simon Svensson, who shows a way to do this if you inherit DynamicObject - for a more forward-looking non-dynamic point of view:

Sorry, but no - but there are types of objects that can be called - for example, delegates.

  Func<int, int> myDelagate = x=>x*2; int four = myDelagate(2) 

By default, the default property is used - it must have at least one parameter, and its access looks like access to an array:

 class Test1 { public int this[int i, int j] { get { return i * j; } } } 

Call

  Test1 test1 = new Test1(); int six = test1[2, 3]; 

Then you can do really stupid things with delegates like this:

 class Test2 // I am not saying that this is a good idea. { private int MyFunc(int z, int i) { return z * i; } public Func<int, int> this[int i] { get { return x => MyFunc(x, i); } } } 

Then the call looks strange:

  Test2 test = new Test2(); test[2](2); // this is quite silly - don't use this..... 
+4
source

This would be like overloading a function call statement (as is possible in C ++). Unfortunately, this is not what is supported in C #. The only objects that can be called similar methods are delegate instances.

+3
source

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


All Articles