问题描述
如果我有这样的方法签名;
If I have a method signature like this;
public void Execute(Action<T> action) {
...
}
但是我想限制它,以便提供的动作只来自MyActions类,在c#中如何实现?
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;
例如我有一个名为MyActions的类;
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.
我不希望任何人可以提供他们必须来自MyActions类。
I do not want it to be possible for anyone to supply an arbitrary action, they must come from the class 'MyActions'.
可以做吗?
Regards,
Ryan。
推荐答案
明确你想要仅接受 MyActions
的成员的意图的一种方式是:
One way to make clear your intent that you want to accept only members of MyActions
would be something like:
public void Execute(Func<MyActions, Action<T>> actionSelector)
你可以像
Execute(actions => actions.SomeAction);
当然这只有在的方法(或委托属性) MyActions
不是静态的。
Of course, this works only if the methods (or delegate properties) of MyActions
are 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:
Execute(ignored => otherAction);
一般来说,这似乎是一件很奇怪的事情。
In general this seems to me like a weird thing to want.
这篇关于如何限制采取Action< T>的方法以允许来自特定类的代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!