KingKerosin
KingKerosin

Reputation: 3851

Pass method as param via expression

I need to have the ability to pass a method of my class (or base-class) to be passed to a base-class method (as it will have to do some more stuff there).

I known about the following posibility: In my base-class I have the method public void Call(Action action) which will simply call action() and do other stuff.

But I wan't some more restrictive as by now I can put everything in this method, e.g. Call(() => string.Format("Some {0}, "text)); But I only want to allow methods of own type or base-type.

I think about something like public void Call(Expression<Func<MyClassType, Action>> expressionToAction) but I don't get the right point here.

Is this even possible? With the expression-param I get the error that the method must return Action which is totally not what I want.

Upvotes: 2

Views: 80

Answers (1)

Alexei Levenkov
Alexei Levenkov

Reputation: 100620

You can't achieve "only methods of this class" at compile time. There is no restriction that would let you do that on generic an non-generic types.

If run-time check is enough - pass an expression (use Action not Func - Expression<Action<T>) and inspect body of the expression similar to Get the name of a method using an expression.

Upvotes: 1

Related Questions