Implicit listing for Func or Action delegates?

C # allows you to define an implicit cast to a delegate type:

class myclass { public static implicit operator Func<String, int>(myclass x) { return s => 5; } public static implicit operator myclass(Func<String, int> f) { return new myclass(); } } 

But, unfortunately, we cannot use this to make the object look like a function:

 var xx = new myclass(); int j = xx("foo"); // error Action<Func<String, int>> foo = arg => { }; foo(xx); // ok 

Is there a good way to force an object of one class to accept function style parameters (arguments) directly on its base instance? Kind of like an indexer, but with parentheses instead of square brackets?

+4
source share
1 answer

No, C # does not allow this as part of the language. Under the covers, the CLI uses the call and callvirt commands to invoke a method or, indirectly, a delegate.

So, unlike Python, where you can instantiate a callable class by declaring a def __call__ method, C # does not have a similar function.

+1
source

All Articles