Python has this magic __call__
method that gets called when the object is called like a function. Does C# support something similar?
Specifically, I was hoping for a way to use delegates and objects interchangeably. Trying to design an API where a user can pass in a list of functions, but sometimes those functions need some initial params, in which case they'd use one of those callable objects instead.
Sure, if you inherit from DynamicObject. I think you're after TryInvoke which executes on obj(...)
, but there are several other method you can override to handle casting, index access (obj[idx]
), method invocations, property invocations, etc.
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;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With