如何创建 public 操作,但保持调用私有?

How do I create a public action, but keep the invoke private?

假设我有这样的操作:

public Action OnSomeAction;

我希望能够从 class 外部订阅此操作,但无法调用它:

OnSomeAction.Invoke();

有没有办法无需将操作设为私有并创建订阅和取消订阅的方法,如下所示:

private Action _someAction;

public void Subscribe(Action listener)
{
    _someAction += listener;
}

public void Unsubscribe(Action listener)
{
    _someAction -= listener;
}

private void Invoke()
{
    _someAction.Invoke();
}

您在寻找 event 吗?

public class MyClass {
  // Let firing event be private 
  private void onMyAction() {
    Action action = MyAction;

    if (action != null)
      action();
  }

  public void FireDemo() {
    onMyAction();
  }

  //TODO: I've put Action, but, probably, EventHandler will be a better choice
  // while event itself (subscribe / unsubscribe) being public
  public event Action MyAction;
}

演示:


MyClass myClass = new MyClass();

var first = () => {Console.WriteLine("I'm the first")};
var second = () => {Console.WriteLine("I'm the second")};
var none = () => {Console.WriteLine("I should not fire")};

myClass.MyAction += first;
myClass.MyAction += second;
myClass.MyAction += none;

// Unsubsribe
myClass.MyAction -= none;

// Direct attempt will NOT compile:
// myClass.MyAction();

myClass.FireDemo();

虽然这看起来很像事件。您也可以使用 Action 来实现它。考虑以下与您建议的代码几乎相同的代码:

private List<Action> _someActionList = new List<Action>();

public void Subscribe(Action listener)
{
    _someActionList.Add(listener);
}

public void Unsubscribe(Action listener)
{
    _someActionList.Remove(listener);
}

private void Invoke()
{
    foreach(action in _someActionList)
    {
        action();
    }
}

我希望这正是您想要做的。如果不是,请进一步说明。