2

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.

KingKerosin
  • 3,639
  • 4
  • 38
  • 77
  • How about a simple virtual method in base class, overridden by a concrete implementation in the subtype? – Tomer Aug 21 '16 at 08:07
  • 1
    `Func` doesn't guarantee anything about the returned `Action`. What are you trying to achieve actually? If you provide a concrete example of why you would want to do this, perhaps there is a better way to do this in the first place. – vgru Aug 21 '16 at 08:23

1 Answers1

1

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.

Community
  • 1
  • 1
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179