If I have a method signature like this;
public void Execute(Action<T> action) {
...
}
but I want to constrain it so that the supplied ‘action’ only comes from the class ‘MyActions’, how can this be achieved in c#?
In order to try and make it clearer;
For example I have a class called MyActions;
public class MyActions {
public void FirstAction<T>(T item) {
...
}
public void SecondAction<T>(T item) {
...
}
}
I have the above method and I want it so that the only actions that the method will accept are those from this class.
I do not want it to be possible for anyone to supply an arbitrary action, they must come from the class ‘MyActions’.
Can it be done?
Regards,
Ryan.
One way to make clear your intent that you want to accept only members of
MyActionswould be something like:You could then call it like
Of course, this works only if the methods (or delegate properties) of
MyActionsare not static.And like I said, this makes your intent clear, but doesn’t actually constraint the methods, someone could still call your method like:
In general this seems to me like a weird thing to want.